21xrx.com
2024-09-20 00:09:46 Friday
登录
文章检索 我的文章 写文章
C++字符串输入
2023-07-05 08:02:34 深夜i     --     --
C++ 字符串 输入

在C++中,输入字符串是一项基本操作,需要掌握正确的方法和技巧。常见的输入字符串方法有以下几种:

1.使用cin和getline函数

• cin函数会从输入流中读取一个单词,以空格作为分隔符,而不是读取整个字符串。

• getline函数会读取一整行,包括空格和换行符。

示例代码如下:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string s1, s2;

  cout << "请输入两个字符串:" << endl;

  cin >> s1;

  getline(cin, s2);

  cout << "您输入的第一个字符串为:" << s1 << endl;

  cout << "您输入的第二个字符串为:" << s2 << endl;

  return 0;

}

2.使用fgets函数

• fgets函数可以从标准输入流(如键盘)读取一行字符串。

• 读取到换行符或达到输入限制时,函数会停止读取。

示例代码如下:


#include <iostream>

#include <cstring>

using namespace std;

int main() {

  char s[100];

  cout << "请输入字符串:" << endl;

  fgets(s, 100, stdin);

  cout << "您输入的字符串为:" << s << endl;

  return 0;

}

需要注意的是,fgets函数会把换行符也读入字符串中,因此需要对其进行处理。

3.使用gets函数

• gets函数可以从标准输入流(如键盘)读取一行字符串。

• 读取到换行符或达到输入限制时,函数会停止读取。

• gets函数已经被废弃,不建议使用,应该使用fgets或scanf函数代替。

示例代码如下:


#include <iostream>

#include <cstring>

using namespace std;

int main() {

  char s[100];

  cout << "请输入字符串:" << endl;

  gets(s);

  cout << "您输入的字符串为:" << s << endl;

  return 0;

}

无论使用哪种方法,都需要注意输入的字符串长度是否超出数组或字符串的限制。在输入之前最好对数组或字符串进行初始化操作。

总之,在C++中,输入字符串并不难,但需要注意一些细节,避免出现意外的错误。掌握了正确的输入字符串方法,可以更加轻松地编写C++程序。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复