user6415386
user6415386

Reputation:

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:

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

Upvotes: 2

Views: 88

Answers (2)

wiomoc
wiomoc

Reputation: 1089

  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:

    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/

Upvotes: 2

user6415386
user6415386

Reputation:

Answer, thanks to 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. TO read the file into my string I used std::getline(readchat, line, ':') which also took care of cutting the string in the :. 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.

Upvotes: 1

Related Questions