从文件中读取单词

问题描述 投票:0回答:1

该功能应该将文件中的任何三个字母单词更改为C ++(如果第一个字母是大写)或C-(如果第一个字母为较低的情况),然后将其打印在输出文件中。 经验:

Cat bat cAr

指望输出

C++ c-- c--

这是以下代码:

void changeThreeLetterWord(ifstream &inStream, ofstream &outStream ){
    string line;
    while (getline(inStream, line)){
        if(!line.empty()){
            char first = line[0];
            if(size(line) == 3){
                if(isupper(first)){
                    outStream << "C++";
                } else if (islower(first)) {
                    outStream << "c--";
                }
            }else{
                outStream << line << endl;
            } 
        } 
    }
}

运行整个代码后,它会完全忽略三个字母单词,而只是打印出相同的确切句子。有什么办法可以解决此问题或改进?

c++ string file
1个回答
0
投票
getline

默认情况下使用newline作为Semperator。要从流中提取单词,您可以使用

>>
#include <iostream>
#include <sstream>
#include <string>

using std::ostream;
using std::istream;
using std::string;
using std::endl;
void changeThreeLetterWord(istream &inStream, ostream &outStream ){
    string word;
    while (inStream >> word) {
        if(!word.empty()){
            char first = word[0];
            if(size(word) == 3){
                if(isupper(first)){
                    outStream << "C++";
                } else if (islower(first)) {
                    outStream << "c--";
                }
            }else{
                outStream << word << endl;
            } 
        } 
    }
}

int main() {
    std::stringstream in{"abc 123 asdg"};
    std::stringstream out;
    changeThreeLetterWord(in,out);
    std::cout << out.str();
}

这个问题仍然存在一个问题,即不会将任何空间放入输出中。我会留给你解决这个问题。
	

© www.soinside.com 2019 - 2025. All rights reserved.