如果这是一个重复的问题,我很抱歉,但我已经尝试寻找答案并且空手而归。所以基本上我只想将字符串(单个单词)添加到向量的后面,然后将存储的字符串显示为单个字符串。我是个菜鸟。
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(int a, char* b [])
{
vector<string> userString;
string word;
string sentence = "";
for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
{
cin >> word;
userString.push_back(word);
sentence += userString[i] + " ";
}
cout << sentence;
system("PAUSE");
return 0;
}
为什么这不起作用?
编辑
int main(int a, char* b [])
{
cout << "Enter a sequence of words. Enter '.' \n";
vector<string> userString;
string word;
string sentence = ""; /
int wordCount = 0;
while (getline(cin, word))
{
if (word == ".")
{
break;
}
userString.push_back(word);
}
for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
{
sentence += userString[i] + " ";
wordCount += 1;
if (wordCount == 8)
{
sentence = sentence + "\n";
wordCount = 0;
}
}
cout << sentence << endl;
system("PAUSE");
return 0;
}
所以我的新程序有效。它只是将值放在向量的后面并将它们打印出 8 个单词到一行。我知道有更简单的方法,但我只是在学习向量,而且我会一步一步来。谢谢你们的帮助。