c++ - 在 C++ 中使用 char 通过文件 I/O 读取文件

标签 c++ arrays

请帮忙!每当它输出数组时,它都会打印垃圾:(我的代码的目的是让它遍历一个长文本文件,该文件有一个转换,如下所示。

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;
}

最佳答案

  1. 您可以通过 str.c_str() 将字符串转换为字符数组/指针 http://www.cplusplus.com/reference/string/string/c_str/ 您可以将其结合到:

    std::string linestr;
    std::getline ( readchat,linestr);
    char * line = linestr.c_str()`
    
  2. 替代方案:使用 readchat.read() 直接读取数组 http://www.cplusplus.com/reference/istream/istream/read/

关于c++ - 在 C++ 中使用 char 通过文件 I/O 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595261/

相关文章:

c++ - 如何加快 C++ 中的矩阵乘法?

C++ 根据条件初始化变量

c++ - 如何重新绑定(bind) Boost.TypeErasure any<...> 对象

python - 使用python将带有俄语字符的二维数组打印到csv

python - 用户选择的变量从列表中删除

javascript - 在 NodeJS 中解析 JSON 对象数组

c++ - 为什么我的代码没有设置变量?

c++ - 具有较少关键点的单应矩阵和图像变换

c++ - 为什么一元加号不跟在括号后面

java - 将整数元素添加到列表 JAVA