Reading string with spaces in c++

后端 未结 3 1287
有刺的猬
有刺的猬 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 16:45

    Solution #1:

    char c;
    cin >> noskipws;    // Stops all further whitespace skipping
    while (cin >> c) {  // Reads whitespace chars now.
        count++;
    }
    

    Solution #2:

    char c;
    while (cin.get(c)) {  // Always reads whitespace chars.
        count++;
    }
    
    0 讨论(0)
  • 2020-12-05 17:09

    Simplest way to read string with spaces without bothering about std namespace is as follows

    #include <iostream>
    #include <string>
    using namespace std;
    int main(){
        string str;
        getline(cin,str);
        cout<<str;
        return 0;
    }
    
    0 讨论(0)
  • 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 >> ...) {
            ...
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题