【问题标题】:Trouble using a loop to add characters to an array of "strings" in c?使用循环将字符添加到 c 中的“字符串”数组时遇到问题?
【发布时间】:2014-02-06 06:49:42
【问题描述】:

所以我尝试了数据类型 char 和数据类型 int。不管 printf 只显示输入单词的第一个字母。例如,如果有人输入 dog,它只会说 'd'。 我的猜测可能是 word[i] 的语法只包含第一个字母,但我不知道如何解决这个问题。 有谁知道如何解决这个问题?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    #define pause system("pause")
    #define cls system("cls")


void getUserWords(int *counter, int words[]){
            int i;

            printf("How many words would you like to enter into the cross word puzzle\n");
            scanf("%i",&*counter);
            for(i=0; i < *counter; i++){
                printf("Please enter word #%i\n",i+1);
                scanf("%s",&words[i]);
                printf("The word %c will be added to the crossword puzzle\n",words[i]);
                pause;
                cls;
            }//end for

            printf("Your all your words have been successfully added to the crossword puzzle");
            cls;
        }//end getUserWords

【问题讨论】:

  • 为什么 counter 是一个函数参数,如果在函数中有 2 行你用用户的输入覆盖它
  • 我会保留它的记录以便在另一个函数中再次使用:)
  • 好的 - 也许最好通过 return 语句将计数传回main,所以在主函数中你可以将这个函数的返回值传递给另一个函数
  • @TimCastelijns“你用用户的输入覆盖它”——这不会发生......只有计数器指向的值被改变,而不是计数器本身。这种方法基本上没有什么问题(除了它应该被称为 counterp,而不是 counter),尽管返回计数器值比传递指向它的指针更干净(除非有多个返回值)。
  • @JimBalter only the value counter points to is changed 这就是我想说的。我以为他想将 counter 的值作为参数传递,我不知道这只是为了跟踪它以便以后重用它

标签: c arrays string char


【解决方案1】:

如果您阅读了与 printf() 和朋友相关的 C 库文档, 你会记得 "%c" 是单个字符的格式字符串。如果 你想打印一个字符串到一个终止 NULL,你应该使用“%s”。

你有:

 printf("The word %c will be added to the crossword puzzle\n",words[i]);

但你应该有

 printf("The word %s will be added to the crossword puzzle\n",words[i]);

另外,确保函数的第二个参数有足够的空间来存储counter 字。

【讨论】:

  • 谢谢谢谢有道理!当我使用 s 时它崩溃并出现错误,我如何确保分配了足够的空间?
  • 对于初学者来说,将您的单词数组声明为字符串数组char* words[] 而不是整数
  • 仍然无法正常工作..当您使用一维数组并使用words[i]将值分配给single position(字符为1字节)时..您需要使用@987654327 @ 或 %s in scanf as words 而不是 words[i]...
  • 嗯,这个答案不好,因为它没有解决 words 的类型......你正在用 %s 打印一个 int
  • @jim-balter 如果你马上给出所有答案,OP 将如何学习 C 的工艺?
【解决方案2】:

int words[] words 是一个整数数组,只能保存指定大小的整数。 现在,当您使用 scanf("%s",&amp;words[i]); 时,您正试图将一个字符串读入一个不正确的每个整数位置。这就是即使您输入字符串也只能存储第一个字符的原因。

【讨论】:

  • ..... 这也意味着 words[] 应该声明为 char*,并在通过 words = calloc(counter * sizeof(char)); 调用你的函数之前调用你的函数你还应该弄清楚你想要多少个单词持有,以及他们可能持有多长时间,以便您得到counter 正确。可能更容易断言您将只接受 n 单词,最多 80 个字符(标准行长度),然后通过 words = calloc(n * 80 * sizeof(char)) 分配
  • 好吧,我要把所有的东西都改成 char,然后试试看,谢谢
猜你喜欢
  • 2013-01-15
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多