大家好,新年快乐,这就是问题所在。我知道我可以将单词(作为字符串)存储在具有足够空间的char数组中。但是我需要知道行何时更改。任何想法如何做到这一点?在特定的示例中,我有一个由3个字符串组成的数组(每个字符串5个字节)。当线路改变时,问题是如何知道的。这是我从一行中取出单词的方式:
int main(void)
{
int i;
char * *array;
array = (char**)malloc(3*sizeof(char*)); //allocation
for(i=0; i<=2; i++){
array[i] = (char*)malloc(5*sizeof(char)); //alocation
}
/* now i store the words */
i = 0;
while(i<=2){
scanf("%s", array[i]);
i++;
}
}
#include <stddef.h>
#include <ctype.h>
#include <stdio.h>
#define SIZEOF_ARRAY(x) (sizeof(x) / sizeof((*x)))
int peek(FILE *stream)
{
return ungetc(fgetc(stream), stream);
}
int main()
{
char words[3][5] = { 0 };
size_t words_read = 0;
for (size_t i = 0; i < SIZEOF_ARRAY(words); ++words_read, ++i) {
if (scanf("%4s", words[i]) != 1)
break;
int ch; // discard non-whitespace characters that exceeded available storage:
while ((ch = peek(stdin)) != EOF && !isspace(ch))
fgetc(stdin);
// discard whitespace until a newline is encountered:
while ((ch = peek(stdin)) != EOF && isspace(ch) && ch != '\n')
fgetc(stdin);
if (ch == '\n') {
puts("NEWLINE!");
fgetc(stdin); // remove the newline from the stream
}
}
for (size_t i = 0; i < words_read; ++i)
printf("%2zu: \"%s\"\n", i, words[i]);
}
你好,我找到了一个解决方案。只是在我得到一个字符串之后,我将使用getchar()来查看它是否为'\ n.btw thnx