逐字输入字符串 我刚开始学习C++。我只是在玩弄它,遇到了一个问题,需要一个字一个字地输入字符串,每个字之间用空格隔开。我的意思是,假设我有 name place animal
作为输入。我想读第一个单词,对它做一些运算。然后读第二个单词,对它做一些运算,然后读下一个单词,依此类推 我试着用getline这样存储整个字符串逐字输入字符串 我刚开始学习C++。我只是在玩弄它,遇到了一个问题,需要一个字一个字地输入字符串,每个字之间用空格隔开。我的意思是,假设我有 name place animal,c++,C++,作为输入。我想读第一个单词,对它做一些运算。然后读第二个单词,对它做一些运算,然后读下一个单词,依此类推 我试着用getline这样存储整个字符串 #include<iostream> using namespace std; int main() { string t; getline(cin,t); cout << t; //just to confirm the input is read correct
#include<iostream>
using namespace std;
int main()
{
string t;
getline(cin,t);
cout << t; //just to confirm the input is read correctly
}
#包括
使用名称空间std;
int main()
{
字符串t;
getline(cin,t);
cout将该行放入stringstream并逐字提取:
#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 */
}
}
#包括
#包括
使用名称空间std;
int main()
{
字符串t;
getline(cin,t);
istringstream iss(t);
字符串字;
while(iss>>word){
/*用词做事*/
}
}
当然,您可以跳过getline部分,直接从cin
逐字阅读
这里可以读取
GETLIN,一次存储整个行,这不是你想要的。一个简单的修复就是有三个变量,并用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;
}
#包括
使用名称空间std;
int main(){
字符串a、b、c;
cin>>a>>b>>c;
//现在你有三个词了
返回0;
}
我不知道你在说什么“操作”,所以我不能帮助你,但是如果它改变了字符,读字符串和索引。C++文档是很好的。至于使用命名空间STD;相对于STD::和其他库,已经有很多说法。试试StAcExobe开始。
(这是为了其他可能提及的人的利益)
您可以简单地使用cin和char数组。cin输入由它遇到的第一个空格分隔
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
#包括
使用名称空间std;
main()
{
字符字[50];
cin>>单词;
while(word){
//用word做一些事情
cin>>单词;
}
}
我尝试使用cin读取。但是由于单词之间用空格分隔,cin似乎只读取第一个单词。一个简单的cin t;cout;显示了这一点。因此我切换到getline。@jrok在您提供的代码上出现编译错误。错误:变量“std::istringstream iss”具有初始值设定项,但不完整type@zack你进来了吗clude
?@jrok“iss”是干什么的?istringstream
到底是什么?一种修改过的字符串类型?字符串中的字数未知。那么有什么方法用cin读取这些字吗?你也可以用getline和消除字符来做一些事情