21xrx.com
2025-06-18 21:59:13 Wednesday
文章检索 我的文章 写文章
C++如何输入多行字符串
2023-07-05 11:28:44 深夜i     90     0
C++ 输入 多行字符串 换行符 getline()函数

如果您正在使用C++,并且需要输入多行字符串,那么您需要了解一些技巧。

在C++中,要输入多行字符串,最简单的方法是使用getline()函数。该函数从输入流中读取一行字符串,直到遇见换行符为止。您可以在循环中使用getline()函数,以便重复读入多行字符串。

以下是使用getline()函数进行多行字符串输入的示例程序:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string input_str;
  while (getline(cin, input_str))
    cout << input_str << endl;
  
  return 0;
}

在上面这个例子中,while循环会一直运行,直到没有更多的输入为止。每次读入一行字符串后,程序会将其打印出来。一旦没有更多的输入,程序就会结束。

除了使用getline()函数,您还可以使用cin.getline()函数进行多行字符串输入。与getline()函数不同的是,cin.getline()函数可以指定读入的最大字符数。下面是一个使用cin.getline()函数进行多行字符串输入的示例程序:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
  char input_str[100];
  while (cin.getline(input_str, 100))
    cout << input_str << endl;
  
  return 0;
}

在上面这个例子中,程序使用了一个char数组来存储输入的字符串。cin.getline()函数每次最多读取99个字符,因为最后一个字符需要留给'\0',即字符串的结束符。

在C++中,如果您需要输入多行字符串,那么您可以使用getline()函数或cin.getline()函数。以上两种方法都可以很好地处理多行输入,并且非常常见。选择哪种方法取决于您的具体需求和个人喜好。

  
  

评论区