我正在自学C++,并正在解决以下问题:
编写一个名为trimfrnt()的函数,可以删除字符串中所有前导空格。使用指针编写该函数,返回类型为void。
我对此问题的尝试如下所示,并尝试了两种方法来解决此问题(您可以看到我的两个函数trimfrnt1()和trimfrnt2())。 trimfrnt1()运行良好,但是我不确定它确切地为什么有效。 我对for循环感到困惑。下面是msg数组的图示:
编写一个名为trimfrnt()的函数,可以删除字符串中所有前导空格。使用指针编写该函数,返回类型为void。
我对此问题的尝试如下所示,并尝试了两种方法来解决此问题(您可以看到我的两个函数trimfrnt1()和trimfrnt2())。 trimfrnt1()运行良好,但是我不确定它确切地为什么有效。 我对for循环感到困惑。下面是msg数组的图示:
|<--ptrMsg--------->|
|<------for loop---->|
0 1 2 3 4 5 6 7
+----+----+----+----+----+----+----+----+
| | | G | R | E | A | T | \0 |
+----+----+----+----+----+----+----+----+
| G | R | E | A | T | | | \0 |
+----+----+----+----+----+----+----+----+
问题1
从我的上图中,由于重叠,我实际上希望输出的文本是:"GREATAT"。但为什么整个字符串都被移动和重新初始化了呢?因为我只循环了5个字母?
问题2
题目要求使用指针,所以我认为trimfrnt1
是作弊,因为我在索引。我试图使用另一种方法trimfrnt2
。但我卡在了while循环中:
// shift characters to beginning of char array
while( *(ptrMsg + count) != '\0' )
{
*ptrMsg = *(ptrMsg + count);
ptrMsg++;
count++;
}
我的代码这一部分无法工作。当我输出*(ptrMsg + count)
时,我得到了正确的字符,但是当我把它赋给*ptrMsg的内容时,我得到了乱码字符。在这种情况下,因为我没有重新初始化剩余的字符,所以我也期望得到"GREATAT"。是否有一种指针方法可以实现这一点呢?
谢谢!
#include<iostream>
#include<iomanip>
using namespace std;
void trimfrnt1(char msg[], int size)
{
char *ptrMsg = msg;
// Find beginning of text
while(*ptrMsg == ' ')
ptrMsg++;
// Copy text to beginning of array
for(int i=0; i < size; i++)
msg[i] = *ptrMsg++;
// Reset pointer to beginning of array
ptrMsg = msg;
// Print array
cout << "new msg1: ";
cout << "\"" << ptrMsg << "\"" << endl;
cout << endl;
return;
}
void trimfrnt2(char msg[], int size)
{
int count = 0; // used to find leading non-white space
char *ptrMsg = msg; // pointer to character array
// find first place of non white space
while( *(ptrMsg + count) == ' ')
count++;
cout << "count = " << count << endl;
// shift characters to beginning of char array
while( *(ptrMsg + count) != '\0' )
{
*ptrMsg = *(ptrMsg + count);
ptrMsg++;
count++;
}
cout << "count = " << count << endl;
// Reset pointer to beginning of array
ptrMsg = msg;
// Print array
cout << "new msg2: ";
cout << "\"" << ptrMsg << "\"" << endl;
cout << endl;
}
int main()
{
char msg[] = " GREAT";
const int size = sizeof(msg)/sizeof(char);
cout << "Orginal msg:\"" << msg << "\"" << endl;
trimfrnt1(msg, size);
return 0;
}
trimfrnt1
函数中,你的for
循环实际上循环次数过多。它循环了size
次,但你从中复制的位置超出了数组的末尾。这会导致未定义行为,在你的情况下(调试器?)似乎可以工作。 - Hulktrimfrnt1
中,请检查复制字符串数据的 for 循环。 - Harshil Sharma