繁体   English   中英

将.txt文件中的文本输出到c ++控制台

[英]output text in .txt file into c++ console

我是编程新手。 我有一个tcms软件,可以将所有数据导出到.txt文件中。 我想输出.txt的C文件++控制台(完全一样在.txt文件),但我所能做的就是这个。 谁能帮我? 这是我的代码:

#include <iostream> 
#include <iomanip>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;

int main() {
    string x;
    ifstream inFile;

    inFile.open("TEXT1.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    while (inFile >> x) {
        cout << x << endl ;
    }

    inFile.close();
}

TEXT1.txt (和我想要的输出)是

WLC013   SIN LEI CHADMIN DEPA      0     0.00     0.00    0.00    0.00     2.00
WLC008   NAI SOO CHADMIN DEPA      0     0.00     0.00    0.00    0.00     2.00
WLC017   SYLVESTER ADMIN DEPA      0     0.00     0.00    0.00    0.00     2.00
WLC004   CHANG KUEIADMIN DEPA      0     0.00     0.00    0.00    0.00     2.00

但我得到这样的输出

WLC013    
SIN LEI CHADMIN DEPA         
0      
0.00      
0.00    
0.00    
0.00      
2.00      
WLC008    
NAI SOO CHADMIN DEPA        
...

是否可以编辑文本文件并为每个列添加标题? 谢谢!

你正在逐字阅读文件,你需要逐行阅读,以获得所需的输出。

while (getline(inFile,x)) {
cout << x << endl ;
}

要添加标题/标题或更好的格式,请参阅setw

在控制台上输出它,然后您可以简单地使用输出重定向>到文件。

假设您的源名称是test.cpp

./test > new_file.txt (linux)

要么

test.exe > new_file.txt (windows)

这是最简单的方法。 还有其他方法。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

int main()
{
char directory[_MAX_PATH + 1];
char filename[_MAX_PATH + 1];

std::cout << "Please provide a directory Path: ";
std::cin.getline(directory, _MAX_PATH);

std::cout << "\nPlease provide a name for file: ";
std::cin.getline(filename, _MAX_PATH);

strcat(directory, filename);

std::ofstream file_out(directory);

if (!file_out) {
    std::cout << "Could not open.";
    return -1;
}

    std::cout << directory << "Was created\n";
    for (int i = 0; i <= 5; ++i) {
        std::cout << "(Press ENTER to EXIT): Please enter a line of text you 
        would like placed, in the document: ";
        char nest[100], *p;
        std::cin.getline(nest, _MAX_PATH);
        p = strtok(nest, "\n|\t|\r");

        while (p != nullptr) {
            p = strtok(nullptr, " ");
            std::cout << " The line (";
            file_out << nest << std::endl;
            std::cout << " )Line was successfully added.\n";
        }

    }
    file_out.close();
    return 0;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM