21xrx.com
2025-07-09 02:49:34 Wednesday
文章检索 我的文章 写文章
如何在C++中输入多行字符串
2023-06-27 05:05:59 深夜i     51     0
输入 多行 字符串 C++ getline()函数

在C++中输入多行字符串是编程中的一项基本操作,通常在读入文件或读取用户输入时需要使用。本文将介绍C++中输入多行字符串的几种方法。

方法一:使用getline()函数

C++标准库提供了一个名为getline()的函数,可以读取一行字符串,直到遇到换行符为止。在循环中多次调用该函数可以读取多行字符串。

示例代码如下:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string line;
  while(getline(cin, line)) // 读入一行
    cout << line << endl;  // 输出
  
  return 0;
}

当然,getline()函数还可以指定读取字符串的分隔符,如果需要的话可以参考相关资料。

方法二:使用cin和字符串数组

可以使用C++中的cin和字符串数组结合使用,循环读入字符串并存储在数组中。

示例代码如下:

#include <iostream>
#include <string>
using namespace std;
const int MAXN = 100;
int main() {
  string str[MAXN];
  int cnt = 0;
  while(cin >> str[cnt]) { // 读入字符串
    cnt++;
  }
  for(int i = 0; i < cnt; i++) { // 输出
    cout << str[i] << endl;
  }
  return 0;
}

需要注意的是,使用该方法读入的每个字符串不能包含空格。

方法三:使用getline()和字符串数组

如果需要读入带有空格的字符串,可以使用getline()和字符串数组结合使用,循环读入字符串并存储在数组中。

示例代码如下:

#include <iostream>
#include <string>
using namespace std;
const int MAXN = 100;
int main() {
  string str[MAXN];
  int cnt = 0;
  while(getline(cin, str[cnt])) { // 读入一行
    cnt++;
  }
  for(int i = 0; i < cnt; i++) { // 输出
    cout << str[i] << endl;
  }
  return 0;
}

总之,以上三种方法都可以在C++中输入多行字符串。在实际开发中,可以根据需要选择合适的方法。

  
  

评论区