簡體   English   中英

如何讀取由空格分隔的多行整數(在 C++ 中)?

[英]How to read input several lines of integers seperated by spaces (in C++)?

所以有Q線。 每行都有由空格分隔的任意數量的整數,我需要處理這些數字。

示例輸入

Q = 4
12 32 4 3 2
1 2 3 4 
0
2 3 1 223 4 2 3

我將每一行作為字符串讀取並將數字提取為字符串,然后使用 atoi 將它們轉換為 int,即,

while(Q>0){
        for(char c:s){
            if (c==' '){
                int x = atoi(temp.c_str());
                temp = "";
                //process x
                continue;
            }
            temp +=c;
        }
        Q--;
    }

當然有更好的方法來做到這一點嗎?

編輯:每行的編號處理方式不同。

例如,說

第 1 行有 1、2、3、4。 第 2 行有 14,15。

然后 1,2,3,4 的處理方式不同,13,14 的處理方式不同。

這就是為什么我不能使用 std::cin 的原因,因為它會忽略所有空格(空格和換行符)。

#include <iostream>

// ...

int x;
while (std::cin >> x)
    ; // process x

編輯您評論的原因:

#include <iostream>

// ...

int x;
char ch;
while (std::cin >> x >> std::noskipws >> ch >> std::skipws) {
    if (ch == '\n')
        ; // process x differently
}

如果您需要面向行的解析並且仍然想使用 iostream 的強大功能,那么我建議您使用std::getlinestd::istringstream 下面的例子

#include <iostream>
#include <sstream>

int main() {
    char ch = '\0';
    std::cin >> ch;
    if (!std::cin || ch != 'Q') return EXIT_FAILURE;
    std::cin >> ch;
    if (!std::cin || ch != '=') return EXIT_FAILURE;
    int Q = 0;
    std::cin >> Q;
    if (!std::cin) return EXIT_FAILURE;
    std::string line;
    std::getline(std::cin, line); // get ready for a new line
    while (Q > 0) {
        if (!std::getline(std::cin, line)) return EXIT_FAILURE;
        std::istringstream iss(line);
        int count = 0;
        int sum = 0;
        int i;
        while (iss >> i) {
            ++count;
            sum += i;
        }
        std::cout << "Found " << count << " integers who's sum was " << sum << '\n';
        Q--;
    }
    std::cout << "Done\n";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM