一次读入若干个字符串 c++
时间: 2023-08-20 20:17:45 浏览: 49
你可以使用 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 循环中,我们不断地读取新的字符串,直到读到输入流的结尾。
相关问题
用c++实现给你若干个字符串,请编程输出每个字符串的子串个数
好的,以下是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string s;
getline(cin, s); // 读取换行符
for (int i = 0; i < n; i++) {
getline(cin, s);
int len = s.size();
int count = len * (len + 1) / 2; // 计算子串个数
cout << count << endl;
}
return 0;
}
```
首先,我们读入一个整数 `n`,表示字符串的个数。接着,我们使用 `getline` 函数读取每个字符串,并计算它的子串个数。由于一个长度为 `len` 的字符串有 `len*(len+1)/2` 个子串,所以我们可以直接计算出子串个数。最后输出结果即可。
希望这个代码能够帮助你解决问题。如果你还有其他问题,请继续提问。
如何输入若干字符串(字符串数量不确定)(用C++)
可以使用 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` 可以读入一整行字符串。