2017-06-03 31 views
-3

我有一个问题,一个字符串的所有小写字符应该被转换成大写字母。但是根据问题,代码中的某些行不应该被改变。我已经写下了下面的代码。如何将字符串的小写字符转换为C++中的大写字符?

#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <ctype.h> 
using namespace std; 

class StringOps { 
public: 
    void stringToUpper(string &s) //This line should not be changed 
    { 
    char c; 
    int i=0; 
    while (s[i]) 
    { 
    c=s[i]; 
    putchar (toupper(c)); 
    i++; 
    } 
    } 
}; 

int main(void) 
{ 
    string str ="Hello World"; 
    StringOps obj; 
    obj.stringToUpper(str); 
    cout << str;   //This line should not be changed 
    return 0; 
    } 

我得到的输出:

HELLO WORLDHello World 

但所需的输出是:

HELLO WORLD HELLO WORLD 

如何使主的

cout<<str; 

声明()打印函数中计算的结果:

void stringToUpper(string &s) 
+0

恩,看起来你想要t o修改'stringToUpper'中的's',而不是只读取它。 – aschepler

+1

你应该设法使'stringToUpper' _change_'s'来代替打印类似的东西。 –

+0

谢谢!我现在明白了我的错误。 –

回答

0

仅适用于ASCII字符较低部分的解决方案。

class StringOps { 
public: 
    void stringToUpper(string& s) //This line should not be changed 
    { 
    for (size_t i = 0; i < s.size(); ++i) { 
     if (s[i] > 96 && s[i] < 123) 
     s[i] -= 32; 
    } 
    } 
}; 

,如果你关心的ASCII表的较高的部分:

class StringOps { 
public: 
    void stringToUpper(string& s) //This line should not be changed 
    { 
    for (size_t i = 0; i < s.size(); ++i) { 
     s[i] = toupper(s[i]); 
    } 
    } 
}; 

如果你有一些多字节编码,如UTF-8,你会需要一些库。

+0

谢谢你的努力! –

0

cout < < str; //此行不应改变

这意味着您必须更改str

无效stringToUpper(字符串& S)//这行不应该改变

好消息,你的方法采取s作为参考。

在你的代码正在做c=s[i];你应该重新指定字符在字符串中s[i] = c

0

你只是打印字符串以使每个字符上的性格,但传递给函数(参考)“字符串s“不会改变。

void stringToUpper(string &s) 

可以添加一条线,使S IN无效stringToUpper(字符串& S)得到改变

s[i] = toupper(c); 

代码看起来

c=s[i]; 
s[i] = toupper(c); 
putchar (toupper(c)); 
i++; 

输出将被

HELLO WORLDHELLO WORLD 
相关问题