[C ++] Input Multiple rows of numbers to an array and multiple rows of arrays.
The input format of a company's pen exam question the day before yesterday is a multi-line number. Each line is separated by a space and ended with a line break number into multiple arrays. In JAVA, there are corresponding functions that directly split a row into an array. I feel that the input method in C ++ is still quite strange. Today I come up with a solution.
Ideas:
Read one character each time to determine whether it is EOF. If it is, it jumps out of the loop;
Not EOF;
When a line break is read, it indicates that a line ends and the array is processed;
The read character. If it is not a space, a temporary string is saved;
If it is a space, the string is converted to an integer and pushed into the array;
Note:
Consecutive space input must be judged; otherwise, a heap of 0 will be entered;
When reading line breaks, you need to save the final temporary string to the array;
Code:
#include<iostream>#include<string>#include<vector>#include<cstdlib>using namespace std;int main() { char flag; while ((flag=getchar())!=EOF) { putchar(flag); string tmpStr; vector<int> buff; char c; while ((c = getchar()) != '\n') { if (c != ' ') tmpStr.push_back(c); else { if (tmpStr != "") { buff.push_back(atoi(tmpStr.c_str())); tmpStr = ""; } } } if(tmpStr!="") buff.push_back(atoi(tmpStr.c_str())); for (auto a : buff) cout << a << ' '; cout << '\n'; }}