学堂 学堂 学堂公众号手机端

在C++中,输入字符串的方式有以下几种: 使用cin输入:可以使用cin对象来输入字符串,但是遇到空格会停止输入,因此不适合输入包含空格的字符串

lewis 2年前 (2023-11-17) 阅读数 6 #技术

在C++中,输入字符串的方式有以下几种:

  1. 使用cin输入:可以使用cin对象来输入字符串,但是遇到空格会停止输入,因此不适合输入包含空格的字符串。
#include<iostream> #include<string> usingnamespacestd; intmain(){ stringstr; cout<<"Enterastring:"; cin>>str; cout<<"Youentered:"<<str<<endl; return0; }
  • 使用getline输入:可以使用getline函数来输入字符串,它可以接受包含空格的字符串。
  • #include<iostream> #include<string> usingnamespacestd; intmain(){ stringstr; cout<<"Enterastring:"; getline(cin,str); cout<<"Youentered:"<<str<<endl; return0; }
  • 使用scanf输入:可以使用scanf函数来输入字符串,但是需要指定格式化字符串"%s"。
  • #include<cstdio> intmain(){ charstr[100]; printf("Enterastring:"); scanf("%s",str); printf("Youentered:%s\n",str); return0; }

    这些是C++中常用的输入字符串的方式,可以根据实际需求选择合适的方式。


    版权声明

    本文仅代表作者观点,不代表博信信息网立场。

    热门