gpt4 book ai didi

c - 终止 While 循环 scanf ("%c",&ch)

转载 作者:行者123 更新时间:2023-11-30 15:11:56 24 4
gpt4 key购买 nike

我想一次读入一个输入字符。我不知道这个输入有多大,所以我没有将一个数组指向输入,而是一次处理每个字符并构建一个链接列表。但我遇到的问题是,在读取最后一个字符后如何终止这个 while 循环?

struct node{
struct node *next;
int data;
};

int main(){

int i; //iterator
char ch;
//char *numberArr = (char*)malloc(1024,sizeof(char*));
struct node* head = NULL;
struct node* curr = NULL;
struct node* tail = NULL;


printf("Please input a number: ");
while (((scanf(" %c",&ch)) != -1)){
printf("%c",ch);
}

最佳答案

如果您想读取所有字符,包括空白字符,请使用:

int c;
while ( (c = getchar()) != EOF )
{
// Use c as a char.
}

如果您想跳过空白字符,请使用:

char c;
while ( scanf(" %c", &c) == 1 )
{
// Use c.
}

请注意在这两种情况下使用 intchar 作为 c 的类型。

关于c - 终止 While 循环 scanf ("%c",&ch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com