I know that I can store words (as strings) in char arrays that have enough space.
In the particular example I have an array of 3 strings that are 5 bytes each.
This is the way I take the words from a line:
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)); // allocation
}
/* now I store the words */
i = 0;
while(i <= 2)
{
scanf("%s", array[i]);
i++;
}
}
How can I know when the line number has changed?
#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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.