c++ - 在 C 和 C++ 中使用 char* 获取字符串输入

标签 c++ c string input

<分区>

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/

相关文章:

c++ - 什么是 "abstractions"?

c++ - 比较从函数返回的两个 std::string 常量(两个 json-spirit get_str()s)1-liner

javascript - 如何将 JSON 字符串转换为 JS 对象并检查属性值?

java - 文字字符串创建与 String 对象创建

c# - 替换多个字符串的更好方法 - C# 中的混淆

c++ - C++ 中的多级继承 (CRTP)

c++ - SHGetKnownFolderItem - 在 Wow64 上失败

c++ - x64 位的 C++/CLI DLL 和 Exe 应用程序崩溃

c - 在c中打印字符串数组的值

c++ - 计算立方体/长方体的边界框/缺失点