为什么字符串不会在c ++中串联

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

我正在尝试使用C ++连接字符串。但是,仅将最后一行连接起来。我不知道为什么。

#include <iostream>
#include <fstream>
#include <bits/stdc++.h> 
#include <string>
using namespace std; 

int main() {

    string tempLine;
    string allWords;
    //char tempLine[] = "";
    //char allWords[] = "";

    ifstream myReadFile("words.txt");

    if (myReadFile.is_open()){
        while (getline(myReadFile, tempLine)){
            cout << tempLine << '\n';
            //allWords = allWords + tempLine;
            allWords.append(tempLine);
            //strcat(allWords,tempLine);
        }
        myReadFile.close();
    }

    cout << "\n\n ----------------- \n\n" <<allWords;

    return 0;
}

这是我的输出:

If you're looking for random paragraphs, you've come to the right place.
When a random word or a random sentence isn't quite enough, the next logical step is to find a random paragraph.
We created the Random Paragraph Generator with you in mind. The process is quite simple.
Choose the number of random paragraphs you'd like to see and click the button.
Your chosen number of paragraphs will instantly appear.

您选择的段落数将立即显示。

c++ string concatenation concat string-concatenation
1个回答
0
投票

据我了解的问题。似乎您正在使用getline功能仅在一行中读取“ words.text”文件。如果您想将单词连接成字符串,请使用以下代码:

int main() {

string tempLine;
string allWords;
//char tempLine[] = "";
//char allWords[] = "";

ifstream myReadFile("Words.txt");

if (myReadFile.is_open()) {
    while (myReadFile >> tempLine) {
        cout << tempLine << " ";
        //allWords = allWords + tempLine;
        allWords.append(tempLine);
        allWords.append(" ");
        //strcat(allWords,tempLine);
    }
    myReadFile.close();
}

cout << "\n\n ----------------- \n\n" << allWords << endl;
system("pause");
return 0;

}

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