21

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 whitespace. What I mean is, suppose I have

   name  place animal 

as the input. I want to read the first word, do some operations on it. Then read the second word, do some operations on that, and then read the next word, so on.

I tried storing the entire string at first with getline like this

    #include<iostream>
    using namespace std;
    int main()
    {
     string t;
     getline(cin,t);
     cout << t; //just to confirm the input is read correctly
    }

But then how do I perform operation on each word and move on to the next word?

Also, while googling around about C++ I saw at many places, instead of using "using namespace std" people prefer to write "std::" with everything. Why's that? I think they do the same thing. Then why take the trouble of writing it again and again?

4

3 回答 3

57

将该行放入字符串流中并逐字提取:

#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 */
    }
}

当然,您可以跳过 getline 部分,直接逐字阅读cin

在这里你可以阅读为什么被using namespace std认为是不好的做法。

于 2013-08-19T16:51:44.023 回答
6

(这是为了其他可能参考的人的利益)

您可以简单地使用cinchar数组。cin 输入由它遇到的第一个空格分隔。

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}
于 2014-07-31T17:39:22.970 回答
1

getline 一次存储整行,这不是您想要的。一个简单的解决方法是拥有三个变量并使用 cin 来获取它们。C++ 将在空格处自动解析。

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

我不知道您在说什么特定的“操作”,所以我无法帮助您,但是如果它正在更改字符,请阅读字符串和索引。C++ 文档很棒。至于使用命名空间std;与 std:: 和其他库相比,已经有很多说法了。在 StackOverflow 上尝试这些 问题以开始。

于 2013-08-19T16:58:24.503 回答