我是C语言的新手,在阅读输入和指针时,我在理解一些基本材料时遇到了一些困难。我想使用一个nextChar()函数来读取和打印我在命令行中输入的字符串中的每个字符。我试着输入"hello“,..It会显示”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;
}
发布于 2013-04-18 16:12:18
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-18 16:04:16
%s
格式说明符指示printf
打印字符数组,直到它找到空终止符。如果要打印单个char
,则应改用%c
。如果这样做,还需要使用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-18 22:57:43
#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;
}
https://stackoverflow.com/questions/16087807
复制相似问题