简体   繁体   English

在C ++中使用char读取具有文件I / O的文件

[英]Reading a file with File I/O using a char in C++

Please help! 请帮忙! Whenever it outputs the array, it prints garbage :( The purpose of my code is for it to go through a long text file, which has a conversion, like this. 每当它输出数组时,它都会打印垃圾:(我的代码的目的是让它通过一个长文本文件,该文件具有转换功能,如下所示。

2016-20-5: Bob: "Whats up!"
2016-20-5: Jerome: "Nothing bro!" 

and for it to take this and break it up to like a format like this: 并将其分解为类似以下格式的格式:

Person's Name: Bob Message Sent: Whats up! Date: 2016-20-5

(BTW there is a file called "char.txt" and if I use a string it works, but I cant use string because some funcs only accept char* ) Here is what I have so far, still trying to make it print out this: (顺便说一句,有一个名为"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. You can convert a String to a char array / pointer via str.c_str() http://www.cplusplus.com/reference/string/string/c_str/ You can combine this to: 您可以通过str.c_str() http://www.cplusplus.com/reference/string/string/c_str/将String转换为char数组/指针您可以将其组合为:

     std::string linestr; std::getline ( readchat,linestr); char * line = linestr.c_str()` 
  2. Alternative: read direct to array with readchat.read() http://www.cplusplus.com/reference/istream/istream/read/ 替代方法:使用readchat.read()直接读取到数组, 网址为http://www.cplusplus.com/reference/istream/istream/read/

Answer, thanks to Loki Astari! 回答,感谢Loki Astari! New code: 新代码:

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

int main()
{
    std::ifstream readchat("chat.txt");
    std::string line;
    while (std::getline(readchat, line, ':'))
    {
        std::cout << line << std::endl;
    }
}

Explanation: Used a string instead of char because it is way more neat and is overall way better. 说明:使用字符串而不是char,因为它更整洁,整体上更好。 TO read the file into my string I used std::getline(readchat, line, ':') which also took care of cutting the string in the :. std::getline(readchat, line, ':')文件读入我的字符串中,我使用了std::getline(readchat, line, ':') ,它还负责在:中剪切字符串。 Then since readchat was read into line, I printed line out and added a endl to make a new line everytime the string was cut. 然后,由于将readchat读入行中,因此我将行打印出来并添加endl,以便在每次剪切字符串时都创建新行。

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

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