Reading getline from cin into a stringstream (C++)

前端 未结 4 1702
自闭症患者
自闭症患者 2020-12-15 08:52

So I\'m trying to read input like this from the standard input (using cin):

Adam English 85
Charlie Math 76
Erica His

4条回答
  •  情歌与酒
    2020-12-15 09:14

    Either you don't have a using namespace std in your code or you're not fully qualifying calls made to the API's in the std namespace with an std:: prefix, for example, std::getline(). The solution below parses CSV instead to tokenize values that have whitespace in them. The logic for stdin extraction, parsing the CSV, and converting grade from string to int are all separated. The regex_token_iterator usage is probably the most complicated part, but it uses pretty simple regex for the most part.

    // foo.txt:
    
    // Adam,English,85
    // Charlie,Math,76
    // Erica,History,82
    // Richard,Science,90
    // John,Foo Science,89
    
    // after compiling to a.exe, run with:
    // $ ./a.exe < foo.txt 
    
    // output
    // name: Adam, course: English, grade: 85
    // name: Charlie, course: Math, grade: 76
    // name: Erica, course: History, grade: 82
    // name: Richard, course: Science, grade: 90
    // name: John, course: Foo Science, grade: 89
    
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    typedef unsigned int uint;
    
    uint stoui(const string &v) {
       uint i;
       stringstream ss;
       ss << v;
       ss >> i;
       return i;
    }
    
    string strip(const string &s) {
       regex strip_pat("^\\s*(.*?)\\s*$");
       return regex_replace(s, strip_pat, "$1");
    }
    
    vector parse_csv(string &line) {
       vector values;
       regex csv_pat(",");
       regex_token_iterator end;
       regex_token_iterator itr(
          line.begin(), line.end(), csv_pat, -1);
       while (itr != end)
          values.push_back(strip(*itr++));
       return values;
    }
    
    struct Student {
       string name;
       string course;
       uint grade;
       Student(vector &data) : 
          name(data[0]), course(data[1]), grade(stoui(data[2])) {}
       void dump_info() {
          cout << "name: " << name << 
          ", course: " << course << 
          ", grade: " << grade << endl;
       }
    };
    
    int main() {
       string line;
       while (getline(cin, line)) {
          if (!line.empty()) {
             auto csv = parse_csv(line);
             Student s(csv);
             s.dump_info();
          }
       }
    }
    

提交回复
热议问题