use*_*200 3 c c++ string input
可能重复:
从带有空格字符的输入中读取字符串?
我在将字符串(技术字符数组)作为输入时遇到问题.假设我有以下声明:
char* s;
Run Code Online (Sandbox Code Playgroud)
我必须使用这个char指针输入一个字符串,直到我点击"输入",请帮忙!Thanx提前.
在C和C++中,您可以使用该fgets
函数,该函数读取直到新行的字符串.例如
char *s=malloc(sizeof(char)*MAX_LEN);
fgets(s, MAX_LEN, stdin);
Run Code Online (Sandbox Code Playgroud)
会做你想要的(在C中).在C++中,代码类似
char *s=new char[MAX_LEN];
fgets(s, MAX_LEN, stdin);
Run Code Online (Sandbox Code Playgroud)
C++还支持std::string
该类,它是一个动态的字符序列.有关字符串库的更多信息:http://www.cplusplus.com/reference/string/string/.如果您决定使用字符串,那么您可以通过编写以下内容来阅读整行:
std::string s;
std::getline(std::cin, s);
Run Code Online (Sandbox Code Playgroud)
在哪里找到:所述fgets
程序可以发现在报头<string.h>
,或者<cstring>
用于C++.该malloc
函数可以在<stdlib.h>
C和<cstdlib>
C++中找到.最后,在文件中找到std::string
具有该std::getline
功能的类<string>
.
建议(对于C++):如果你不确定使用哪一个,C风格的字符串,或者std::string
根据我的经验,我告诉你字符串类更容易使用,它提供了更多实用程序,而且它也快得多比C风格的字符串.这是C++入门的一部分:
As is happens, on average, the string class implementation executes considerably
faster than the C-style string functions. The relative average execution times on
our more than five-year-old PC are as follows:
user 0.4 # string class
user 2.55 # C-style strings
Run Code Online (Sandbox Code Playgroud)