[C ++] Input Multiple rows of numbers to an array and multiple rows of arrays.

Source: Internet
Author: User

[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';    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.