字符串没有存储在向量中?
String not getting stored in vector?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string n, m;
vector <string> dingdong;
cin >> n;
dingdong.push_back(n);
cin >> m;
dingdong.push_back(m);
for (int i = 0; i <2; i ++) {
cout << dingdong[i];
}
return 0;
}
当我 运行 程序时,我输入 "hay sombody there" 并按回车键。该程序打印 "haysombody." 所以我想如果我将 'i' 增加到 3 程序将打印 "haysombodythere" 但不,主要只是崩溃。为什么会发生这种情况,我该如何存储整个字符串(包括空格)?
"why is this happening and how do I make it so that the entire strings (including the spaces) get stored?"
要从输入中获取多个单词,您应该使用
std::getline(cin,n);
而不是
std::cin >> n;
白色 space 默认用作分隔符,因此每次调用 std::istream
的 operator>>
只会存储读取到下一个白色 space 的文本] 字符.
请查看您程序的完全修复版本here。
此外,如果你真的想逐字读入 vector
,你可以使用循环这样做
string word;
vector <string> dingdong;
while(cin >> word) {
if(word.empty) {
break;
}
dingdong.push_back(word);
}
然后像
一样打印出来
for (int i = 0; i < dingdong.size(); ++i) {
cout << dingdong[i];
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string n, m;
vector <string> dingdong;
cin >> n;
dingdong.push_back(n);
cin >> m;
dingdong.push_back(m);
for (int i = 0; i <2; i ++) {
cout << dingdong[i];
}
return 0;
}
当我 运行 程序时,我输入 "hay sombody there" 并按回车键。该程序打印 "haysombody." 所以我想如果我将 'i' 增加到 3 程序将打印 "haysombodythere" 但不,主要只是崩溃。为什么会发生这种情况,我该如何存储整个字符串(包括空格)?
"why is this happening and how do I make it so that the entire strings (including the spaces) get stored?"
要从输入中获取多个单词,您应该使用
std::getline(cin,n);
而不是
std::cin >> n;
白色 space 默认用作分隔符,因此每次调用 std::istream
的 operator>>
只会存储读取到下一个白色 space 的文本] 字符.
请查看您程序的完全修复版本here。
此外,如果你真的想逐字读入 vector
,你可以使用循环这样做
string word;
vector <string> dingdong;
while(cin >> word) {
if(word.empty) {
break;
}
dingdong.push_back(word);
}
然后像
一样打印出来for (int i = 0; i < dingdong.size(); ++i) {
cout << dingdong[i];
}