gpt4 book ai didi

c - 将字符保存在数组中

转载 作者:行者123 更新时间:2023-11-30 16:37:32 25 4
gpt4 key购买 nike

我想做一个程序,要求用户提供一个字符,然后输入...直到他想通过按 Enter 键停止并且没有字符。

然后,程序会说:“你给了角色......”

例如:

give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')

结果:您给出的字符:kl

我的代码不能工作,因为当我按下回车键时,什么也没有发生。这是代码:

#include <stdio.h>
#define N 1000

int main() {

int i = 0;
int j = 0;
char str[N];

while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}

printf("The string is: ");

while (j < i) {

printf("%s", str[j]);
j += 1;
}

return 0;
}

最佳答案

您可以使用c = getchar();c = fgetc(stdin)函数来实现:

#include <stdio.h>
#define N 1000

int
main ()
{
int i = 0;
int j = 0;
int c;

char str[N];

while (1)
{
c = fgetc(stdin); // or c = getchar();

if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}

}

printf ("The string is: %s", str);

return 0;
}

输出:

This is my string!                                                                                                                                                                                                                                
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!

或者您可以使用原来的 scanf("%s", &str1);

#include <stdio.h>
#define N 1000

int main ()
{
int i = 0;
int k = 0;
int c;
int len;

char str[N];
char str1[N];

scanf("%s", &str1);

len = strlen(str1);

for(k = 0; k < len; k++)
{
c = str1[k];

if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}

printf ("The string is: %s", str);

return 0;
}

输出:

12345                                                                                                                                                                                                                                             
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345

关于c - 将字符保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857199/

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