Reading string with spaces in c++

后端 未结 3 1294
有刺的猬
有刺的猬 2020-12-05 16:30

How can I read input line(type string) with whitespace? I tried getline but it goes into infinite loop. Following is my code.

#include 
#incl         


        
3条回答
  •  遥遥无期
    2020-12-05 17:10

    "How can I read input line(type string) with whitespace?"

    std::string line;
    if (std::getline(std::cin, line)) {
        ...
    }
    

    Note that apart from checking the return value of std:getline call, you should also avoid mixing >> operator with std::getline calls. Once you decide reading the file line by line, it seems to be cleaner and more reasonable to just make one huge loop and do the additional parsing while using string stream object, e.g.:

    std::string line;
    while (std::getline(std::cin, line)) {
        if (line.empty()) continue;
        std::istringstream is(line);
        if (is >> ...) {
            ...
        }
        ...
    }
    

提交回复
热议问题