如何使输出看起来更像我的文字?

时间:2014-11-22 16:35:44

标签: c++

对于我的作业实验室,我应该:

  

定义一个名为textLines的类,用于存储文本行列表     (每行可以指定为字符串或c字符串,无论您喜欢哪种方式)     使用动态数组存储列表     此外,您应该拥有一个指定列表长度的私有数据成员    创建一个以文件名作为参数的构造函数,并使用文件中的行填充列表。

还有更多,但这些功能与问题无关。

到目前为止我的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

// Define class called textLines (used to store list of lines)
class textLines
{
public:
    // Main Constructor
    textLines(ifstream& myfile1){

        pointer = new string[stringsize];

        if (myfile1.fail()) {
            cout << "File failed to open.\n";
            exit(1);
        }
        else
            for (int index = 0; index < stringsize; index++) {
                myfile1 >> pointer[index];
            }
    }
    // Constructor that takes an integer parameter that sets the size of an empty list.
    textLines(int){
        pointer = new string[0];
    }
    // Deconstructor
    ~textLines(){
        delete[] pointer;
    }

    void printArray();


private:
    ifstream infile;
    ofstream outfile;
    static int stringsize;
    string* pointer;
};

// Begin Main Function
int main(){

    string myfile = "Lab3Text.txt";

    ifstream infile(myfile);

    textLines text(infile);
    text.printArray();


    return 0;
}
// End Main


int textLines::stringsize = 1000;

void textLines::printArray(){

    for (int index = 0; index < stringsize; index++) {
        cout << pointer[index];
    }

}

这就是我的文本文件:

Hello World
Hello World
Hello World

我的输出是这样的,但是:

Output: HelloWorldHelloWorldHelloWorld

什么是一个简单的解决方案,我可以让我的输出看起来更像我的文本文件,在行中?

2 个答案:

答案 0 :(得分:0)

只需将endl(结束行)添加到输出中。

void textLines::printArray(){

    for (int index = 0; index < stringsize; index++) {
        cout << pointer[index] << endl;
    }

}

答案 1 :(得分:0)

按以下行修改您的代码:     文件&gt;&gt;指针[指数]; 至     getline(文件,指针[index]; 和     cout&lt;&lt;指针[指数]; 至     cout&lt;&lt;指针[index]&lt;&lt; '\ n'; 为什么? getline()读取一行,而不只是一个单词,'\n'在输出中提供一个新行。

请重新考虑stringsize的值,因为如果您的文件包含较少的行,则打印出垃圾。更多的“C ++风格”是成员vector<string> lines;

string input;
while(getline(file, input) lines.push_pack(input);

输入和

for (size_type i = 0; i < lines.size(); ++i)
  cout << lines[i] << '\n';

输出。当与赋值运算符一起使用时,当前表单中带有裸指针的类很容易出现内存泄漏(请参阅Rule of Three)。