我在程序编写过程中,经常会遇到读入数据的问题,大概这类问题分为两种,一种是从控制台读取,一类是从文件读取,我这里收集了一些常见的读取方法,以供参考。
控制台读取:
情景一、有一个程序要求我们输入一个数组,数组的个数已给定或者要求先给出个数,然后输入数据。
代码:
#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介绍,使用方法与例子