0

我是 C 新手。在阅读输入和指针时,我在理解一些基本材料时遇到了一些麻烦。我想使用 nextChar() 函数来读取和打印我在命令行中输入的字符串的每个字符。我尝试输入“hello”..它显示“hello”6 次。有人能告诉我为什么会这样吗?我该如何解决?感谢您的时间!

#include <stdio.h>
#include <assert.h>
char nextChar(char* ptr)
{
    static int i = -1;
    char c;
    ++i;
    c = *(s+i);
    if ( c == '\0' )
        return '\0';
    else
        return c;
}

void display(char* ptr)
{
    assert(ptr != 0);

    do
    {
        printf("%s", ptr);

    } while (nextChar(ptr));
}


int main(int argc, const char * argv[])
{
    char* ptr=argv[1];

    display(ptr);
    return 0;
}
4

3 回答 3

3

%s格式说明符指示打印printf一个字符数组,直到找到一个空终止符。如果%c要打印单个char. 如果这样做,您还需要使用nextChar.

或者,更简单地说,您可以更改display为直接迭代字符串中的字符

void display(char* ptr)
{
    assert(ptr != 0);

    do
    {
        printf("%c", *ptr); // print a single char
        ptr++; // advance ptr by a single char

    } while (*ptr != '\0');
}

或者,等效但不太明显的指针算术

void display(char* ptr)
{
    int index = 0;
    assert(ptr != 0);

    do
    {
        printf("%c", ptr[index]);
        index++;

    } while (ptr[index] != '\0');
}
于 2013-04-18T16:04:15.817 回答
1

nextchar 函数可以减少:

char nextChar(char* ptr)
{
    static int i = 0;
    i++;
    return (*(ptr+i));
}

并显示到

void display(char* ptr)
{
    assert(ptr != 0);
    char c = *ptr;

    do
    {
        printf("%c", c);

    } while (c = nextChar(ptr));
}
于 2013-04-18T16:12:18.210 回答
1
#include <stdio.h>
#include <assert.h>

char nextChar(const char* ptr){
    static int i = 0;
    char c;

    c = ptr[i++];
    if ( c == '\0' ){
        i = 0;
    }
    return c;
}

void display(const char* ptr){
    char c;
    assert(ptr != 0);

    while(c=nextChar(ptr)){
        printf("%c", c);
    }
}

int main(int argc, const char * argv[]){
    const char* ptr=argv[1];

    display(ptr);
    return 0;
}
于 2013-04-18T22:57:43.137 回答