【发布时间】:2015-06-08 23:05:51
【问题描述】:
我有一个如下的 C 代码:
char* text;
get(text); //or
scanf("%s",text);
但我尝试运行它会中断。因为我没有给出text 的大小。
为什么我没有给出text 的尺寸,因为我不知道尺寸是多少
用户将要输入的文本。
那么,在这种情况下,我该怎么办?
如果我不知道字符串的长度,如何阅读文本?
【问题讨论】:
-
使用getline
我有一个如下的 C 代码:
char* text;
get(text); //or
scanf("%s",text);
但我尝试运行它会中断。因为我没有给出text 的大小。
为什么我没有给出text 的尺寸,因为我不知道尺寸是多少
用户将要输入的文本。
那么,在这种情况下,我该怎么办?
如果我不知道字符串的长度,如何阅读文本?
【问题讨论】:
你可以试试这个
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s = malloc(1);
printf("Enter a string: \t"); // It can be of any length
int c;
int i = 0;
/* Read characters until found an EOF or newline character. */
while((c = getchar()) != '\n' && c != EOF)
{
s[i++] = c;
s = realloc(s, i+1); // Add space for another character to be read.
}
s[i] = '\0'; // Null terminate the string
printf("Entered string: \t%s\n", s);
free(s);
return 0;
}
注意:切勿使用gets 函数读取字符串。它不再存在于标准 C 中。
【讨论】:
1 byte(尽管在每个架构上一个字节不一定是 8 位)。