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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14022720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:54:30  来源:igfitidea点击:

take string input using char* in C and C++

c++cstringinput

提问by user1916200

Possible Duplicate:
Reading string from input with space character?

可能的重复:
从带有空格字符的输入中读取字符串?

I am facing problem in taking a string(technically character array) as input. Suppose i have the following declaration:

我在将字符串(技术上是字符数组)作为输入时遇到问题。假设我有以下声明:

 char* s;

I have to input a string using this char pointer till i hit "enter", please help! Thanx in advance.

我必须使用这个字符指针输入一个字符串,直到我点击“输入”,请帮忙!提前谢谢。

回答by Rontogiannis Aristofanis

In both C and C++ you can use the fgetsfunction, which reads a string up to the new line. For example

在 C 和 C++ 中,您都可以使用该fgets函数,它读取一个字符串直到新行。例如

char *s=malloc(sizeof(char)*MAX_LEN);
fgets(s, MAX_LEN, stdin);

will do what you want (in C). In C++, the code is similar

会做你想做的事(在 C 中)。在C++中,代码类似

char *s=new char[MAX_LEN];
fgets(s, MAX_LEN, stdin);

C++ also supports the std::stringclass, which is a dynamic sequence of characters. More about the string library: http://www.cplusplus.com/reference/string/string/. If you decide to use strings, then you can read a whole line by writing:

C++ 也支持std::string类,它是一个动态的字符序列。有关字符串库的更多信息:http: //www.cplusplus.com/reference/string/string/。如果您决定使用字符串,那么您可以通过编写以下内容来阅读整行:

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

Where to find:the fgetsprocedure can be found at the header <string.h>, or <cstring>for C++. The mallocfunction can be found at <stdlib.h>for C, and <cstdlib>for C++. Finally, the std::stringclass, with the std::getlinefunction are found at the file <string>.

在哪里找到:所述fgets程序可以发现在报头<string.h>,或者<cstring>用于C ++。该malloc函数可以在<stdlib.h>C 和<cstdlib>C++ 中找到。最后,std::string阶级,与std::getline功能在文件中找到<string>

Advice(for C++):if you are not sure which one to use, C-style string or std::string, from my experience I tell you that the string class is much more easy to use, it offers more utilities, and it is also much faster than the C-style strings. This is a part from C++ primer:

建议(对于 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

回答by linuxchip

First thing is to take input into this string you have to allocate memory. After that you can use gets or fgets or scanf

第一件事是将输入输入到这个字符串中,你必须分配内存。之后,您可以使用 get 或 fgets 或 scanf

回答by mic4ael

If you think about C++, cin.getline()might be useful.

如果您考虑 C++,cin.getline()可能会有用。

回答by user1767304

You can use cin>>variable_name; if input is without space. For input with space use gets(variable_name) in c++

您可以使用 cin>>variable_name; 如果输入没有空格。对于带空格的输入,在 C++ 中使用 gets(variable_name)

回答by MOHAMED

the sshould be allocated before starting filling on it

s应该就可以开始填充前被分配

1) If you do not know in advance the size of inputed string you can use realloc

1)如果您事先不知道输入字符串的大小,您可以使用 realloc

char* s = calloc(1,sizeof(char));
char t;
int len;
while(scanf("%c", &t)==1)
{
  if(t== '\n')
     break;
   len = strlen(s);
   s= realloc(s,len+1);
   *(s+len) = t;
   *(s+len+1) = '
char s[256] // Let's assume that the max length of your input string is 256

scanf("%[^\r\n]",s) // this will read your input characters till you heat enter even if your string contains spaces
'; }

2) Now If you know in advance the size of your input string max length, you can read directly your string into an array of char with scanf in this way:

2)现在如果您事先知道输入字符串最大长度的大小,则可以通过这种方式使用 scanf 将字符串直接读入字符数组:

char *ptr = NULL, *temp_ptr = NULL;
int c = 0, chcount = 0, enter_pressed = 0;
do{
   c = fgetc(stdin);
   if (c != '\n' || c != -1){
     chcount++;
     if (ptr == NULL){
         ptr = malloc(sizeof(char) + chcount + 1);
         if (ptr != NULL) ptr[chcount] = c;
         else printf("ABORT!\n");
     }else{
         temp_ptr = realloc(ptr, chcount + 1);
         if (temp_ptr != NULL){
            ptr = temp_ptr;
            ptr[chcount] = c;
         }else{
            // OK! Out of memory issue, how is that handled?
            break;
         }
     }
   }else{
      enter_pressed = 1;
   }
}while (!enter_pressed);
ptr[chcount] = '##代码##'; // nul terminate it!

回答by t0mm13b

Hmmm, since the OP has stated:

嗯,因为 OP 已经声明:

I have to input a string using this char pointer till i hit "enter"

我必须使用这个字符指针输入一个字符串,直到我点击“输入”

Thought I'd give this a shot, top of my head, this is a dynamic buffer, using mallocand reallocusing pointers. However, it may contain bugs, but the gist is there! Nitpicky aside...

我想我会试一试,我的头顶,这是一个动态缓冲区,使用mallocrealloc使用指针。但是,它可能包含错误,但要点就在那里!除了挑剔...

Apologies if the code does look awful... ::)

如果代码看起来很糟糕,请道歉...... ::)

##代码##