ACM模式输入输出处理

发布时间 2023-08-14 11:37:50作者: 无形深空

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

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

直接一个while循环

输入
1 5
10 20

输出
6
30
while(cin>>a>>b)
    {
        cout<<a+b<<endl;
    }

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

输入
2
1 5
10 20

输出
6
30

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;   //{"1,2,3,4,5"};
    std::string line;
    
    int size;
    cout<<"要输入的行数: ";
    cin>>size;
    while (std::getline(cin, line, '\n')&&size>0) // 以'\n'为分隔符
    {
        // 使用 std::stringstream 分割字符串
        std::stringstream ss(line);
        std::string token;
        while (std::getline(ss, token, ',')) // 以','为分隔符
        {
            
            vec.push_back(std::stoi(token));
        }
        size--;
    }

输入字符串

示例1
输入例子:
abc ab
输出例子:
1
示例2
输入例子:
abc ac
输出例子:
0