逐字输入字符串 [英] taking input of a string word by word

查看:149
本文介绍了逐字输入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习C ++。我只是玩弄它,遇到了一个问题,涉及接受一个字符串的字输入,每个字由空格分隔。我的意思是,假设我有

 名称place动物

作为输入。我想读第一个单词,做一些操作就可以了。然后读第二个字,做一些操作,然后读下一个字,等等。



我尝试用getline存储整个字符串,如下



 #include< iostream> 
using namespace std;
int main()
{
string t;
getline(cin,t);
cout<< t; //只是为了确认输入是否正确读取
}

操作每个单词并移动到下一个单词?



此外,因为我是新的,这可能是一个愚蠢的问题,地方,而不是使用使用命名空间std人们更喜欢写std ::
与一切。为什么?我认为他们做同样的事情。

解决方案

将该行放入一个字符串流中,并逐字提取单词:

  #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 逐字读取。 >

在这里,您可以阅读为什么使用命名空间std 视为不良做法


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, since I am new, this might seem a stupid question but 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?

解决方案

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.

这篇关于逐字输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆