我刚刚开始学习C++。我只是在玩它,遇到了一个问题,涉及逐字输入字符串,每个单词用空格分隔。我的意思是,假设我有
name place animal
作为输入。我想读取第一个单词,对其进行一些操作。然后读取第二个单词,对其进行一些操作,然后读取下一个单词,依此类推。
我尝试首先用 getline 存储整个字符串,如下所示
#include<iostream>
using namespace std;
int main()
{
string t;
getline(cin,t);
cout << t; //just to confirm the input is read correctly
}
那么如何对每个单词执行操作并转到下一个单词呢?
另外,在谷歌搜索 C++ 时,我在很多地方看到,人们更喜欢写“std::”,而不是使用“using namespace 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
直接地。
在这里你可以阅读why is using namespace std被认为是不好的做法。 https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)