c++ - 如何使用迭代器?

标签 c++ string for-loop if-statement iterator

我正在尝试使用迭代器更改字符串中的字符。它会更改空格之前的字符,但会删除该空格之后的字符。

怎么了?

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    cout<<"Enter a string : ";
    cin>>s;

    for (auto it = s.begin(); it != s.end() && !isspace(*it);++it)
      *it = toupper(*it);

    cout<<s; // capitalize the current character
    return 0;
}

输出:

Enter a string : abc abc
ABC

最佳答案

for语句中的条件不正确

for (auto it = s.begin(); it != s.end() && !isspace(*it);++it)
 *it = toupper(*it);

当遇到空白时,循环停止迭代。

您应该在循环体内的 if 语句中移动第二个子表达式。例如

for (auto it = s.begin(); it != s.end();++it)
 if ( !isspace( ( unsigned char )*it) ) *it = toupper( ( unsigned char )*it);

而不是语句

cin>>s;

使用

std::getline( std::cin, s );

关于c++ - 如何使用迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504673/

相关文章:

java - 在我向 TextView 添加一些单词后,我尝试使用一个简单的按钮更改 java android 中字符串的某些部分,但它不起作用

Excel VBA 将项目添加到动态创建的组合框

loops - 如何在 Kotlin 循环内更改 for 循环的计数器变量值?

ios - 在 Swift 中填充多维数组

php - 如何使用php将字符串转换成数组

c++ - 为什么 ranges::view_interface<T>::size 需要移动构造函数

c++ - boost-asio 作为守护进程的 "template"

c++ - 为什么 nl_langinfo(CODESET) 与语言环境字符映射不同?

c++ - 在 C++ 中原则上不可能进行严格的模板评估吗?

c# - 二进制到字符串为二进制?