gpt4 book ai didi

c - 指针上的字符串 scanf

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

我想接收用户的姓名。之后,我想在屏幕上打印收到的姓名。例如:

--扫描:

roy
john
malw

--打印:

roy
john
malw

代码:

#include <stdlib.h>
#include <stdio.h>

int main ()
{
int i;
char *aer[4];
char *(*pter)[4] = &aer;

for(i=0;i<4;i++)
scanf(" %s",&(*pter)[i]); //read strings

for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*pter)[i]); //write strings

system ("pause");
return 0;
}

最佳答案

scanf 可能不是正确的函数,请尝试使用 strtok:

#include <string.h>
#include <stdio.h>

#define MAX_LINE_LENGTH 80
#define MAX_TOKENS_PER_LINE 4

int main () {
int i;
char *aer[MAX_TOKENS_PER_LINE];
char s[MAX_LINE_LENGTH];

do {
if (!fgets(s, MAX_LINE_LENGTH, stdin)) return -1;

i = 0;
while (
i != MAX_TOKENS_PER_LINE
&& (aer[i] = strtok(i ? 0 : s, " \n"))
) i++;

i = 0;
while (
i != sizeof(aer) / sizeof(aer[0])
&& aer[i]
) {
fprintf(stdout, "%s\n", aer[i]);
i++;
}
}
while (aer[0]);

return 0;
}

另请注意,您忘记为要解析的标记分配内存。在我的示例中,内存分配给整行,strtok 返回指向其中子字符串的指针。

关于c - 指针上的字符串 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29833191/

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