我为什么要把它拿出去?

时间:2015-02-14 03:44:02

标签: c++

我已经在这个项目上工作了很长时间,我觉得我已经接近完成了。但是,我的代码输出了一些奇怪的东西,我找不到问题。

预期产出:

  

检查我的读者是否有效,这是一个快乐的方法!   一条快乐的鳄鱼在快乐的公园里,一头快乐的母牛在一条快乐的围巾上吹着鼻子。你是一个快乐的八角形吗?

实际输出:

  

这是检查我的读者是否正常工作的快乐!   很高兴   很开心

如何使以下代码符合我的预期?

#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
#include <locale>

using namespace std;

void
usage(char *progname, string msg){
    cerr << "Error: " << msg << endl;
    cerr << "Usage is: " << progname << " [filename]" << endl;
    cerr << " specifying filename reads from that file; no filename reads standard input" << endl;
}
string capitalization(string word,string adj){
    for(int i = 0; i <= word.length(); i++){
        if(isupper(word[i])){
            for(int j = 0; j <= adj.length(); j++){
                adj[j] = toupper(adj[j]);
                return adj;
            }
        }
        else if(isupper(word[0])){
            for(int j = 0; j <= adj.length(); j++){
                adj[j] = tolower(adj[j]);
                return adj;
            }
        }
        else{
            for(int j = 0; j <= adj.length(); j++){
                adj[j] = tolower(adj[j]);
                return adj;
            }
        }
    }

}

int main(int argc, char *argv[]){
        string adj;
        string file;
        cin >> adj;
        cin >> file;
        string line;
        string articles[14] = {"a","A","an","aN","An","AN","the","The","tHe","thE","THe","tHE","ThE","THE"};
        ifstream rfile;
        rfile.open(file.c_str());
        if(rfile.fail()){
            cerr << "Error while attempting to open the file." << endl;
            return 0;
        }
        string::size_type pos;
        string word;
        string words[1024];
        while(getline(rfile,line)){
            istringstream iss(line);
            for(int i = 0; i <= line.length(); i++){
                iss >> word;
                words[i] = word;
                for(int j = 0; j <= 14; j++){
                    if(word == articles[j]){
                        string article = word;
                        iss >> word;
                        pos = line.find(article);
                        //cout << pos << endl;
                        string adjec = capitalization(word,adj);
                        int position = (pos + word.length());
                        line.insert(position, " " + adjec);
                        continue;
                    }
                }
            }
        cout << line << "\n";
        }
}

1 个答案:

答案 0 :(得分:1)

这可能无法解决您的任何问题,但......

这些行中的逻辑是错误的。

       istringstream iss(line);
        for(int i = 0; i <= line.length(); i++){
            iss >> word;

我们说你的行是

This is a test.

对于这一行,line.length()是15,但是没有15个字。你需要的是

        istringstream iss(line);
        while ( iss >> word ) {