【问题标题】:Reading Both Individual Characters of Strings and the Strings themselves Pointed to by a String Array读取字符串的单个字符和字符串数组指向的字符串本身
【发布时间】:2014-09-29 23:53:04
【问题描述】:

在下面的代码中,我试图将字符串数组“char *wordArray[20]...”传递到 main 上面的函数中,该函数旨在查找 wordArray 中包含用户输入字符的所有字符串,并打印每个这样的字符串。函数“findWords”被定义为期望一个常量字符串数组、它的长度和用户输入字符,因为该数组将是只读的。按照我正在使用的文本中的示例,底部是从指向字符串的指针中读取单个字符以及从指针数组中读取字符串的方法的组合。

#include <stdio.h>
#include <stddef.h>
#include <ctype.h>

int arrLength = 0; // Global variable dec. and initialization


void findWords ( const char *c[], int length, char letter ) {

size_t element = 0;
size_t count = 0;

for (element = 0; element < length; element++) {

    for (count = 0; c[count] != '\0'; count++) {

        if (c[count] == letter) {

            printf("%s", c[element]);

        }

        else {

            printf("%s", c[count]);
        }
    }

    count++;
}

return;

} // End function findWords



int main (void) {

{ // Begin Problem 3

    // step 1: printf "Problem 3"
    puts("Hiya");

    // step 2: create a string array of 3 pointers to strings containing at this point, random  
       words.

    const char *wordArray[3] = { "cake", "foxtrot", "verimax" };


    char usrInp; // Holds user-input letter.

    // step 3: "Input a letter from the user."
    // This do...while loop repeats until the user has entered either a lower- or uppercase    
letter.

    do {

        puts("Please enter one lowercase letter - any you'd like\n"); // One string argument 
calls for output function puts(); rather than printf();

        usrInp = tolower ( getchar() );


    } while ( isalpha (usrInp) == 0 );

    findWords( wordArray, arrLength, usrInp );

} // End Problem 3
} // End function main

【问题讨论】:

  • 似乎有几个问题,其中一个是编译器返回了关于我比较“c[count]”和“letter”的警告,它被识别为 int 类型。我需要一点帮助来了解如何比较 char var 中的字符。到字符串数组中包含的字符串中的字符。注意:请忽略块引用中 *wordArray[] 的大小。

标签: c arrays string pointers


【解决方案1】:

在 findWords :

for (element = 0; element < length; element++) {
    for (count = 0; c[element][count] != '\0'; count++) {
        if (c[element][count] == letter) {
            printf("%s\n", c[element]);
            break;
        }
    }
}

主要:

arrLength = sizeof(wordArray)/sizeof(*wordArray);//arrLength = 3;
findWords( wordArray, arrLength, usrInp );

【讨论】:

  • 很好地使用sizeof(wordArray)/sizeof(*wordArray)
  • 很好的答案,BLUEPIXY;非常感谢!然而,我很困惑,我没有在文本中遇到这种技术。再次,非常有帮助。
【解决方案2】:

c[count] 是 char*,这意味着您无法将其与 char 进行比较。此指针仅保存当前字符串的地址。您需要遍历该字符串才能检查字母。
在您的代码中您需要更改:

if (c[element][count] == letter)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2012-04-08
    • 2021-10-27
    相关资源
    最近更新 更多