taking input of a string word by word

后端 未结 3 1233
小鲜肉
小鲜肉 2020-12-02 13:53

I just started learning C++. I was just playing around with it and came across a problem which involved taking input of a string word by word, each word separated by a white

相关标签:
3条回答
  • 2020-12-02 14:20

    getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

    #include <iostream>
    using namespace std;
    
    int main() {
        string a, b, c;
        cin >> a >> b >> c;
        //now you have your three words
        return 0;
    }
    

    I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

    0 讨论(0)
  • 2020-12-02 14:29

    Put the line in a stringstream and extract word by word back:

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    int main()
    {
        string t;
        getline(cin,t);
    
        istringstream iss(t);
        string word;
        while(iss >> word) {
            /* do stuff with word */
        }
    }
    

    Of course, you can just skip the getline part and read word by word from cin directly.

    And here you can read why is using namespace std considered bad practice.

    0 讨论(0)
  • 2020-12-02 14:36

    (This is for the benefit of others who may refer)

    You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

    #include<iostream>
    using namespace std;
    
    main()
    {
        char word[50];
        cin>>word;
        while(word){
            //Do stuff with word[]
            cin>>word;
        }
    }
    
    0 讨论(0)
提交回复
热议问题