如何输入若干字符串(字符串数量不确定)(用C++)
时间: 2023-10-07 20:12:21 浏览: 67
可以使用 C++ 中的 `vector<string>` 容器来存储若干字符串,然后使用循环读入每个字符串。以下是一个示例代码:
```C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
string input;
// 循环读入字符串,直到输入空行为止
while (getline(cin, input) && input != "") {
strings.push_back(input);
}
// 输出读入的字符串
for (string str : strings) {
cout << str << endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个 `vector<string>` 容器来存储若干字符串,然后使用 `while` 循环读入每个字符串。循环的终止条件是输入空行,即用户不再输入字符串为止。最后,我们使用 `for` 循环遍历容器中的每个字符串,并输出它们。
注意,我们使用 `getline(cin, input)` 函数来读入一行字符串,而不是使用 `cin >> input`,这是因为 `cin` 在读入字符串时会遇到空格就停止,而 `getline` 可以读入一整行字符串。
相关问题
c++实现一次读取若干字符串
可以使用 `vector<string>` 来存储若干个字符串,然后使用 `getline()` 函数逐行读取输入,直到达到指定的字符串个数为止。具体实现如下:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int n; // 读取的字符串个数
cin >> n;
vector<string> strs; // 用 vector 存储若干个字符串
for (int i = 0; i < n; i++) {
string s;
getline(cin, s); // 逐行读取字符串
strs.push_back(s);
}
// 输出读取的字符串
for (int i = 0; i < n; i++) {
cout << strs[i] << endl;
}
return 0;
}
```
需要注意的是,在读取 `n` 值后需要使用 `cin.ignore()` 函数忽略掉输入流中的换行符,否则会影响后面的 `getline()` 函数的正常运行。
一次读入若干个字符串 c++
你可以使用 C++ 中的 getline 函数来一次读入若干个字符串,示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
while (getline(cin, line)) {
cout << line << endl;
}
return 0;
}
```
在这个示例代码中,我们使用了 getline 函数来从标准输入流中读取一行字符串,并将其存储在名为 line 的字符串变量中。然后,我们使用 cout 输出该字符串,并在结尾加上一个换行符。在 while 循环中,我们不断地读取新的字符串,直到读到输入流的结尾。