一个c++程序的疑惑. 输入字串符,输出却是数字!

软件和网站开发以及相关技术探讨
回复
me
帖子: 972
注册时间: 2007-09-14 19:51

一个c++程序的疑惑. 输入字串符,输出却是数字!

#1

帖子 me » 2007-09-27 18:28

c++ primer 第四版 3.14的习题:
读入一段文本到vector对象,每个单词存储为vector中的一个元素,把vector对象中每个单词转化为大写字母.输出vector对象中转化后的元素,每八个单词为一行输出.

代码: 全选

#include<iostream>
#include<string>
#include<vector>
#include<cctype>
int main()
{
    using namespace std;
    string temp;
    vector<string> a;
    while(cin>>temp)
        a.push_back(temp);

    for(vector<string>::size_type index = 0;index!=a.size();++index)
    {
        if(index % 8 == 0)
            cout<<endl;
        for(string::size_type index2 = 0;index2!=a[index].size();++index2)
            cout<<toupper(a[index][index2])<<endl; //输出其大写形式
        cout<<" ";
    }
    return 0;
}
运行输入字串符,输出却是数字!
例如输入“jin”:
qiu@ubuntu:~$ ./a.out
jin

74
73
78
qiu@ubuntu:~$
me
帖子: 972
注册时间: 2007-09-14 19:51

#2

帖子 me » 2007-09-27 19:03

知道了,原来不能这样用:
cout<<toupper(a[index][index2])
但是我不明白为什么不能这样用:toupper()不是返回字母的大写形式吗?再用cout输出,不感觉有什么不对,为什么就不能这样用呢?
还有为什么会输出数字呢?
我是菜鸟
哪位高手帮忙解释下
谢谢
头像
FFFrog
帖子: 621
注册时间: 2006-05-12 23:28
来自: 江西乐平
联系:

#3

帖子 FFFrog » 2007-09-27 19:18

代码: 全选

/* Return the uppercase version of C.  */
extern int toupper (int __c) __THROW;
这个函数返回的是int值,你需要将返回值显式转换成char,编译器才会将它作为ASCII码来识别。
上次由 FFFrog 在 2007-09-27 20:26,总共编辑 1 次。
me
帖子: 972
注册时间: 2007-09-14 19:51

#4

帖子 me » 2007-09-27 19:59

谢谢。
是不是要用printf()和 %c ?
cout有没有类似的方法?
头像
FFFrog
帖子: 621
注册时间: 2006-05-12 23:28
来自: 江西乐平
联系:

#5

帖子 FFFrog » 2007-09-27 20:03

cout<<(char)toupper(a[index][index2])<<endl;

显式转换是这样。
me
帖子: 972
注册时间: 2007-09-14 19:51

#6

帖子 me » 2007-09-27 20:19

再次感谢 :)
回复