输入一个正整数n,然后再输入n行字符串。
基于C++具体实现代码如下,需注意的是,当输入n并敲回车,产生的换行符会继续存在于输入流缓存区中,相当于输入流里有了数据,如此则第一遍getline(cin,s) 读入的就是换行符,从而导致只能输入n-1行字符串(可自己验证),所以将输入流中的换行符去掉即可。
针对此问题,可采用 cin 的一个方法,即 ignore(),此方法会忽略掉当前输入流中的数据;也可采用头文件 cstdio 下的 getchar(),其会读取输入流中的一个字符。
具体代码如下:
#include
#include
#include
#include
using namespace std;
int main()
{
string s;
vector<string> arr;
int n;
cin >> n;
//cin.ignore();
getchar();
while (n--)
{
getline(cin, s);
arr.push_back(s);
}
cout << "输入内容:" << endl;
for (auto& val : arr)
{
cout << val << endl;
}
return 0;
}
运行结果:

注:关于此处内容也可点击博客进行查看!
将包含空格的一行字符串按空格分开:
实现代码:
#include
#include
#include
#include
#include
using namespace std;
int main()
{
string s = "hello world and how are you!";
cout << "源字符串: " << s << endl << endl;
stringstream ss;
ss << s;
vector<string> ans;
string tmp;
while (ss >> tmp)
ans.push_back(tmp);
cout << "分割后单词:" << endl;
for (auto& val : ans)
cout << val << endl;
return 0;
}
运行结果:

注:此方法很简单,但会使用较多开销,因为需要将输入字符串转换为字符串流并从字符串流读取到目标字符串.
当然也可以直接用循环遍历、string类中的find()与substr()去进行分割,此处就不贴对应代码了~