gpt4 book ai didi

c - 输出正确的单词

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

我需要输出一个单词,我输入了其中的一些数字..我不知道如何为一个单词分配一个数字。这是我使用 func strtok() 来打破我的单词句子,然后我迷路了.. 例如:“hhh jjjj kkkkk llllll”我输入 3 它输出:kkkkk

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

int main()
{
char str[80],*p;
char sp[20]=" ";
int i,n=0,num;
printf("Enter your line: ");
gets(str);
p=strtok(str,sp);
while (p!=NULL){
for(i=0;i<p;i++){
printf("%s - [%d]\n",p,i+1);
p=strtok(NULL,sp);
n=p;
}
n++;
}
printf("n: ");
scanf("%d",&num);
if(num==n){
printf("%s",p);
}

return 0;
}

最佳答案

1) 不应使用 gets 。这就是为什么这里是 fgets(str, sizeof str, stdin);

2) 我输入一个单词的编号之前我开始标记该行

3)主要算法如下:

while (p != NULL && n < num){
if(++n == num){
printf("%s\n", p);
break;
}
p=strtok(NULL, sp);
}

在我的循环中,当用户输入一个数字并且如果它等于 num 时,n 在找到单词时上升,因此它会跳出循环并打印它。

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

int main(void){
char str[80], *p;
const char *sp = " \n";
int n = 0, num = 0;

printf("Enter your line: ");
fgets(str, sizeof str, stdin);
printf("n: ");
scanf("%d", &num);

p = strtok(str, sp);
while (p != NULL && n < num){
if(++n == num){
printf("%s\n", p);
break;
}
p=strtok(NULL, sp);
}

return 0;
}

关于c - 输出正确的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41427773/

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