将.txt文件中的文本输出到c++控制台中
output text in .txt file into c++ console
我是编程新手。我有一个tcms软件,可以将所有数据导出到.txt
文件中。我想在c++控制台上输出.txt
文件(与.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
(以及所需的输出i)是
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
(窗口)
这是一种最简单的方法。也可以有其他方式。
#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 createdn";
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;
}
相关文章:
- C++:将控制台输出存储在宏中更好吗
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- C++控制台应用程序阻止退出
- 如何修复此iFile以将.txt输出到控制台
- 为什么控制台要求输入,即使代码中没有输入
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 控制台输出在 Qt5 中未正确显示
- C++出现控制台错误.我无法识别源代码的问题
- C++程序不会从 Windows 控制台运行
- 有人可以向我解释为什么控制台输出 0 吗?
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- Win32 API 控制台光标在 WriteConsole 后不移动
- 如何获取控制台窗口的宽度?
- 如何在 Win32 C++控制台应用程序中调用 UWP 类库
- 如何从Windows控制台调用.exe(C++)以在不同的目录(或任何目录)中创建文件夹?
- 来自Visual Studio中控制台项目的exe文件?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 使用 std::string_view 的子字符串控制台输出