2

我正在尝试将句子从大写转换为小写。我也写了一个代码,但是当出现空格时我会停下来。我该如何解决这个问题并转换整个句子?这是我的代码

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char str[100];
    cin>>str;
    for(int i=0;i<strlen(str);i++)
    {
        if(str[i]>='A'&&str[i]<='Z')
        {
            str[i]=str[i]+32;
        }
    }
    cout<<str<<endl;
    return 0;
}
4

4 回答 4

1

这是因为输入运算符>>,它在空间上中断。如果你想读一整行,那么用std::getlineto read into astd::string代替。

然后阅读C++ 标准算法,例如std::transform。此外,std::tolower不会修改任何不是大写字母的内容,因此这是一个很好的功能。

于 2013-11-09T15:43:48.863 回答
0

The reason input stops at whitespace is because formatted input is delimited by whitespace characters (among others). You will need unformatted I/O in order to extract the entire string into str. One way to do this is to use std::istream::getline:

std::cin.getline(str, 100, '\n');

It's also useful to check if the input succeeded by using gcount:

if (std::cin.getline(str, 100, '\n') && std::cin.gcount())
{
    ...
}

But in practice it's recommended that you use the standard string object std::string which holds a dynamic buffer. To extract the entire input you use std::getline:

std::string str;

if (std::getline(std::cin, str)
{
    ...
}
于 2013-11-09T16:05:58.130 回答
0

该错误是因为operator>>分隔空格。另一种方法是使用getline. 请参见以下示例:

#include <cstring>
#include <iostream>
#include <string>

int main() {
  std::string s;

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

  std::cout << "Original string: " << s << std::endl;

  if (!std::cin.fail()) {
    const int len = strlen(s.c_str());

    for (size_t i = 0; len > i; ++i) {
      if ((s[i] >= 'A') && (s[i] <= 'Z'))
        s[i] = s[i] - 'A' + 'a';
    }
  }

  std::cout << "New string: " << s << std::endl;

  return 0;
}
于 2013-11-09T15:48:06.460 回答
0

这是使用变换函数执行此操作的示例之一。

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string str;

    if (getline(cin, str))
    {
        transform(str.begin(), str.end(), str.begin(), ptr_fun<int, int>(toupper));
    }

    cout << str << endl;
    return 0;
}
于 2016-11-30T14:19:19.870 回答