0

我在学校分配的一些工作上遇到了一些麻烦。我被告知要编写一个修改字符的程序。我可以做到这一点。我只是不知道如何使用指针。我对此进行了研究,并找到了一些解决方案。但它们不能满足任务的需要。我被告知要定义一个完全像这样的函数:

int stripWhite(char *userInput)

所以我做了。唯一的问题是,我相信这会复制价值。并且不修改实际值。所以这是从我的程序中挑选出来的一些代码:

在 main 中,我声明了我的 char,并使用 cin.getline 来收集我的输入。然后我叫stripwhite。然后我cout我的char。价值永远不会改变。作业说 stripwhite 需要完全按照上面的定义。我在这里不知所措。有什么帮助吗?

char userInput[100];
int spaces = 0;
cin.getline(userInput,99);
spaces = stripWhite(userInput);
cout << userInput;
4

3 回答 3

4

stripWhite被定义为接收一个指向 char 的指针,它不会复制原始数据——它传递一个指向原始数据的指针,因此*userInput在 of 内部进行stripWhite修改将修改其地址被传递的原始字符串。

简单演示:

#include <iostream>

void modify(char *input) { 
    *input = 'a';
}

int main() { 
    char data[] = "ABCD";

    std::cout << data << "\n";
    modify(data);
    std::cout << data << "\n";
    return 0;
}

结果:

ABCD
aBCD
于 2013-05-13T05:32:10.543 回答
1

您的函数需要一个字符指针。根据函数名称和用法,该函数可能旨在将字符缓冲区作为输入并删除所有空格,同时返回删除的空格数。

所以基本上,你必须遍历缓冲区,并在跳过空格的同时向下移动内容。最简单的方法是维护两个指针并从一个指针复制到另一个指针。

这是我的做法(警告,未经测试)。显然,由于这是一项作业,您需要编写自己的代码,但希望这个示例能够消除您的任何误解。

int stripWhite(char* userInput){

    auto inpos = userInput;
    auto outpos = userInput;
    int count = 0;

    while(*inpos){
        if(*inpos != ' '){
            *outpos = *inpos;
            ++outpos;
        } else {count++;}
        ++inpos;
    }

    *outpos = '\0';
    return count;
}
于 2013-05-13T05:34:29.750 回答
0

如果需要,您可以使您的函数接收指向 char 的指针并更改所有内容。

char stripWhite(char **ptr){
*ptr = "String";
}

char *string;
stripWhite( &string );
cout<< string <<endl;
于 2013-05-13T05:43:46.263 回答