2011-10-20 wcdj


问题:
在Linux下编写程序,要求打开一个文本文件,读入一行内容,将其中的小写转换成为大写,其他不变,文件名作为命令行参数输入。
来源:
http://topic.csdn.net/u/20111020/12/9e5b23fc-15fe-4d78-b2a8-693337c8c34e.html

一种省事的方法:

#include <iostream>
#include <string>
#include <fstream>
#include<algorithm>
using namespace std;

int main(int argc, char* argv[])
{
	 if (argc != 2) 
	{
		cout << "usage: " << argv[0] << "filename" << endl;
		return 1;
	}
	ifstream ifs(argv[1]);
	if (!ifs) 
	{
		cout << "Error: to open the file: " << argv[1] << endl; 
		return 1;
	}
	string str;
	while (getline(ifs, str))// get each line, if u want all, u can use ifs >> str
	{
		transform(str.begin(), str.end(), str.begin(), ::toupper);// note !
		cout<< str <<endl;
	}
	ifs.close();

    return 0;
}

输出结果:

gerryyang@xxx:~/test> ./toUpper od.txt
ABADFFAADD
DFDADDDAAF
ASDASDIOSS
DD778AADDF


注意:
在VS2010中,下面代码没有问题:
transform(str.begin(), str.end(), str.begin(), toupper);// ok
而在 gcc 4.1.2 中,则必须指明toupper:
transform(str.begin(), str.end(), str.begin(), ::toupper);// note !
否则,在编译的时候会出现如下的错误:
gerryyang@xxx:~/test> g++ -g -Wall -o toUpper toUpper.cpp
toUpper.cpp: In function 'int main(int, char**)':
toUpper.cpp:24: error: no matching function for call to 'transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)'

The reason is that g++ is picking the wrong toupper, try ::toupper.
More details:
http://www.codeguru.com/forum/showthread.php?threadid=489969

在Linux中,或者:

#include <iostream>
#include <string>
#include <fstream>
#include<algorithm>
//using namespace std;
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::ifstream;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "usage: " << argv[0] << "filename" << endl;
        return 1;
    }
    ifstream ifs(argv[1]);
    if (!ifs)
    {
        cout << "Error: to open the file: " << argv[1] << endl;
        return 1;
    }
    string str;
    while (getline(ifs, str))
    {
        transform(str.begin(),str.end(),str.begin(),toupper);
        cout<< str <<endl;
    }
    ifs.close();

    return 0;
}

A really portable solution is to write a wrapper, e.g.,

inline char charToLower(char c)
{
    return std::tolower(c);
}

// ...
transform(str.begin(), str.end(), str.begin(), charToLower);



Logo

更多推荐