ACM模式输入输出处理

1.1. getline(istream is,string str,以该符号结束)

默认以'\n'为换行符

1.2. cin

遇到 \n会停止读取 但是不会读出来

此时这个\n还在, 如果继续cin, 没问题; 但如果使用getline()就会让getline()认为自己读了一行空数据.

解决: 可以用getchar()跳过

2.1. 数组长度确定, 多组数据

在测试的时候没有写循环, 得在自己的代码中写循环

输入
1 5
10 20

输出
6
30
int MySum(int a, int b)
{
	return a+b;
}

while(cin>>a>>b)
    {
        cout<<MySum(a,b)<<endl;
    }

第一个数表示组数的, 直接给个size,然后for循环

输入
2
1 5
10 20

输出
6
30

2.2. 数组长度不确定, 单组数据

','分割

两个getline()第一个分割一行到stringstream中, 第二个根据','分割

输入例子:
1,5,7,9
2,3,4,6,8,10
输出例子:
1,2,3,4,5,6,7,8,9,10
    std::vector<int> vec;
    int size = 0;
    cout<<"要输入的行数: ";
    cin>>size;
    getchar();

    std::string line;
    for (int i=0;i<size&&getline(cin, line, '\n');i++) // 以'\n'为分隔符
    {
        // 使用 std::stringstream 分割字符串
        std::stringstream ss(line);
        std::string token;
        while (std::getline(ss, token, ',')) // 以','为分隔符
        {  
            vec.push_back(std::stoi(token));
        }
    }

    cout<<"vec.size() = "<<vec.size()<<endl;

    // 输出 vector<int>
    for (const auto& num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

有指出某行的长度的, 使用cin; 否则考虑用getline()

🍅 看到一个总结得很好的

posted @ 2023-08-14 11:32  无形深空  阅读(124)  评论(0编辑  收藏  举报