请帮忙!每当它输出数组时,它都会打印垃圾:(我的代码的目的是让它遍历一个长文本文件,该文件有一个转换,如下所示。
2016-20-5: Bob: "Whats up!"
2016-20-5: Jerome: "Nothing bro!"
并让它采用这个并将其分解为如下格式:
Person's Name: Bob Message Sent: Whats up! Date: 2016-20-5
(顺便说一句,有一个名为 "char.txt"
的文件,如果我使用 string
它可以工作,但我不能使用 string
因为有些函数只接受 char*
)
这是我到目前为止所拥有的,仍在尝试让它打印出来:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
ifstream readchat;
readchat.open("chat.txt");
const int MAX = sizeof(readchat);
char line[MAX];
char *colon;
colon = strtok(line, ":");
while (!readchat.eof())
{
while (colon != NULL)
{
cout << line;
colon = strtok(NULL, ":");
}
}
system("pause");
return 0;
}
最佳答案
您可以通过
str.c_str()
将字符串转换为字符数组/指针 http://www.cplusplus.com/reference/string/string/c_str/ 您可以将其结合到:std::string linestr; std::getline ( readchat,linestr); char * line = linestr.c_str()`
替代方案:使用
readchat.read()
直接读取数组 http://www.cplusplus.com/reference/istream/istream/read/
关于c++ - 在 C++ 中使用 char 通过文件 I/O 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595261/