字符串怎样在c++中输入

如题所述

提供六种字符串输入方法:

用法一:最常用、最基本的用法,输入一个数字:

用法二:接受一个字符串,遇“空格”、“Tab”、“回车”都结束:

用法三:cin.get(字符变量名)可以用来接收字符:

用法四:cin.get(字符数组名,接收字符数)用来接收一行字符串,可以接收空格

用法五:getline(),getline() // 接受一个字符串,可以接收空格并输出,需包含“#include<string>”

用法六:getchar()

getchar()//接受一个字符,需包含“#include<string>

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2019-09-24

C++中几个输入函数包括:cin、cin.get()、cin.getline()、getline()、gets()。

1.cin最基本,也是最常用的用法,输入一个数字:

cin>>a>>b;

2.cin.get()

用法:cin.get(字符变量名),可以用来接收字符。

3.cin.getline() 

接受一个字符串,可以接收空格并输出。

cin.getline(m,5);

4.getline() 

接受一个字符串,可以接收空格并输出,需包含“#include<string>”。

5.gets() 

接受一个字符串,可以接收空格并输出,需包含“#include<string>”。

#include<iostream>

getline(cin,str);

扩展资料:

C++编程语言互换流中的标准输出流:

cout输出函数,需要iostream支持,常用于使用I/O控制符 。

比如:

int a;

cin >> a;

cout << a << endl;

cout << "请输入一个数字,按回车结束" << endl;

return 0;

由于cout会对输出的内容进行缓冲,所以输出的内容并不会立即输出到目标设备而是被存储在缓冲区中,直到缓冲区填满才输出。一般输出的话,有三种情况会进行输出:刷新缓存区、缓存区满的时候和关闭文件的时候。

参考资料:cin-百度百科

getline函数-百度百科

gets函数-百度百科

本回答被网友采纳
第2个回答  推荐于2017-09-23

c++可以使用如下方式输入字符串:
方式一,使用cin>>操作符输入:

#include <iostream>
using namespace std;
void main()
{
char s[50];//字符数组,用于存放字符串的每一个字符
cout<<"Please input a string"<<endl;
cin>>s;
cout<<"The string you input is"<<s<<endl;
}


方式2,使用cin.get函数输入:

#include <iostream>
using namespace std;
void main()
{
char s[50];//字符数组,用于存放字符串的每一个字符
cout<<"Please input a string"<<endl;
cin.get(s,50);//当输入是Enter键时,结束输入
cout<<"The string you input is:"<<s<<endl;
}

第3个回答  2009-03-09
加上#include<string.h>头文件
可用gets()函数输入。(可输入带空格的字符串)
如:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char p[30];
gets(p);
puts(p); //输出字符串
return 0;
}
第4个回答  推荐于2017-09-02
这个方法很多,楼上将的是 C 的兼容模式,可以达到你的要求,另外:

#include <iostream>
#include <string>

int main()
{
std::string str;

std::cout << "please enter a string." << std::endl;

std::cin >> string;

std::cout << "your enter is:"<< str << std::endl;

return 0;
}

这是一种方法,不过不能读入空白(包括空格,制表符等),想要读入空白,看下面:

#include <iostream>
#include <string>

int main()
{
std::string str;

std::cout << "please enter a string." << std::endl;

std::getline(std::cin, string);

std::cout << "your enter is:"<< str << std::endl;

return 0;
}

多动手去实验。本回答被提问者采纳