<分区>
Possible Duplicate:
Reading string from input with space character?
我在将字符串(技术上是字符数组)作为输入时遇到问题。 假设我有以下声明:
char* s;
我必须使用这个字符指针输入一个字符串,直到我点击“输入”,请帮忙! 提前致谢。
<分区>
Possible Duplicate:
Reading string from input with space character?
我在将字符串(技术上是字符数组)作为输入时遇到问题。 假设我有以下声明:
char* s;
我必须使用这个字符指针输入一个字符串,直到我点击“输入”,请帮忙! 提前致谢。
最佳答案
在 C 和 C++ 中,您可以使用 fgets
函数,它读取一个字符串直到新行。例如
char *s=malloc(sizeof(char)*MAX_LEN);
fgets(s, MAX_LEN, stdin);
会做你想做的事(在 C 中)。在C++中,代码类似
char *s=new char[MAX_LEN];
fgets(s, MAX_LEN, stdin);
C++ 还支持 std::string
类,它是一个动态的字符序列。关于字符串库的更多信息:http://www.cplusplus.com/reference/string/string/ .如果你决定使用字符串,那么你可以通过写来读取整行:
std::string s;
std::getline(std::cin, s);
在哪里可以找到: fgets
程序可以在标题 <string.h>
中找到, 或 <cstring>
对于 C++。 malloc
函数可以在 <stdlib.h>
找到对于 C,和 <cstdlib>
对于 C++。最后,std::string
类,与 std::getline
函数可在文件 <string>
中找到.
建议(针对 C++):如果您不确定使用哪一个,C 风格的字符串或 std::string
,根据我的经验,我告诉你字符串类更易于使用,它提供了更多的实用程序,而且它也比 C 风格的字符串快得多。这是 C++ primer 的一部分:
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
关于c++ - 在 C 和 C++ 中使用 char* 获取字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14022720/