我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?

I'm trying to use a while loop to remove letters from a string until there are none left. What am I doing wrong here?

本文关键字:什么 错了 在这里 删除 字符串 循环 while      更新时间:2023-10-16
#include<iostream>
#include<string>
using namespace std;
int main() {
string word;
cout << "please enter a word: ";
getline(cin, word);
int str_size;
word.size() = str_size;
// the line above says "word must be modifiable". new to coding so not sure how to fix it?
// also haven't tested anything below this point yet.
while (str_size) {
word.resize(str_size - 1, '');
}
string end;
getline(cin, end);
return 0;
}

谁能解释我在这里做错了什么。我只是走错了路吗?

在这一行:

word.size() = str_size;

您正在尝试为.size()返回的临时值赋值。但是,operator=需要在左侧有一个左值(即具有名称的变量(。

所以你需要的是:

str_size = word.size();

要实际从字符串中删除字母,您可以使用一些算法,例如std::remove_if来避免编写任何循环。