我在程序編寫過程中,經常會遇到讀入數據的問題,大概這類問題分為兩種,一種是從控制臺讀取,一類是從文件讀取,我這里收集了一些常見的讀取方法,以供參考。
控制臺讀取:
情景一、有一個程序要求我們輸入一個數組,數組的個數已給定或者要求先給出個數,然后輸入數據。
代碼:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;int main()
{cout << "請輸入數組的個數" << " ";int n;cin >> n;int *a = new int[n];for (int i = 0; i < n;i++){cin >>a[i];}cout << "輸入的數據為" << " ";for (int i = 0; i < n; i++){cout <<a[i] << " ";}delete[]a;a = nullptr;return 0;
}
情景二、不斷輸入數字,然后求和
分析:這個問題的難點在于不知道輸入數組的個數。當你輸入數字或者字符串后,回車,按ctrl+z結束輸入
代碼:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;int main()
{cout << "Enter numbers: ";int sum = 0;int input;while (cin >> input)sum += input;cout << "Last value entered = " << input << endl;cout << "Sum = " << sum << endl;return 0;
}
輸入:
Enter numbers: 45
78
45
^Z
Last value entered = 45
Sum = 168
請按任意鍵繼續. . .
#include "iostream"
#include "string"
using namespace std;
int main()
{string word;while (getline(cin, word))cout << word << endl;return 0;
}
輸入:
ajdskalld
ajdskalld
nacjkncklsa
nacjkncklsa
^Z
請按任意鍵繼續. . .
或者:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{istream_iterator< string > is(cin);istream_iterator< string > eof;vector< string > text;copy(is, eof, back_inserter(text));sort(text.begin(), text.end());ostream_iterator< string > os(cout, " ");copy(text.begin(), text.end(), os);return 0;
}
輸入:
acsnkalc
acnkasm
^Z
acnkasm acsnkalc 請按任意鍵繼續. . .
情景三、讀入如下格式的數據:
3 ? ? 5 ? ? ?6
5 ? ?6 ? ? ? 7
5 ? ?4 ? ? ? 4
即多行數據,每行數據間以空格隔開。
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;int main()
{vector<string> stringlist;string str;cout << "請輸入數字,每行三個" << endl;while (getline(cin,str)){stringlist.push_back(str);}int data;for (int i = 0; i < stringlist.size();i++){stringstream s(stringlist[i]);s >> data;cout << data<<" ";s >> data;cout << data << " ";s >> data;cout << data << endl;}return 0;
}
輸入:
請輸入數字,每行三個
1 5 6
2 3 4
7 5 6
^Z
1 5 6
2 3 4
7 5 6
請按任意鍵繼續. . .
從文件讀取:
情景一、同樣是上述數據,讀入文本數據,并輸出。
3 ? ? 5 ? ? ?6
5 ? ?6 ? ? ? 7
5 ? ?4 ? ? ? 4
#include <iostream>
#include <fstream>
#include <iterator>
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;int main()
{vector<string> stringlist;string str;ifstream infile("inputfile.txt");while (getline(infile, str)){stringlist.push_back(str);}int data;for (int i = 0; i < stringlist.size(); i++){stringstream s(stringlist[i]);s >> data;cout << data << " ";s >> data;cout << data << " ";s >> data;cout << data << endl;}return 0;
}
參考文獻:
1.如何判斷cin輸入結束?
2.【C++】輸入流cin方法
3.C++ stringstream介紹,使用方法與例子