Help with code.

Hello guys, I need help:
Let's say that in a txt file named hot.txt, I have this:
12,23,32
And with ifstream I want to take those number, adding one by one as integers in a linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
                    ifstream myList;
                    char* p= new char;
                    cin>>p;
                    myList.open(p);

                    if(myList.is_open()) {
                            char* x =new char;
                            while( myList.eof() == false ) {
                                    myList.get(x,256,','); // dafaq
                                    int num=atoi(x);
                                    list ->addOrdered(num);

                                    }
                            }
                    else {
                            cout <<"ERROR"<<endl;

                            }

                    myList.close();


I know this part is quite wrong that why Im asking for help:
1
2
3
  myList.get(x,256,','); // dafaq
        int num=atoi(x);
        list->addOrdered(num);

What I wanted to do is to stop before each comma and take that character and store it in the linked list and continue until the end of the file, but I couldnt.

Thanks a lot for any given help!

Last edited on
1
2
3
                    char* p= new char;
                    cin>>p;
                    myList.open(p);


p is a pointer to a single char. If you enter "hot.txt\n" for line 4, you will exceed the bounds of the memory you allocated, causing undefined behavior and bad things will happen. You have the same issue with x.
Cire, but if I put cin>>*p, it gives em an error!
And also with *x, It wont read any number D:

So how do you think I can fix that?
Also I know this part is way too wrong:
1
2
3
  myList.get(x,256,','); // dafaq
 int num=atoi(x);
ist ->addOrdered(num);
Last edited on
Cire, but if I put cin>>*p, it gives em an error!
And also with *x, I wont read any number D:


I didn't suggest that cin >>*p was the solution to your problems.

p points to a single char. You need it to point to more than a single char. Manipulating your single char, whether it is *p or *x is not going to get you the results you're looking for.

Presumably you're familiar with arrays. Use them. Or better yet, use std::string.
Ok, I will use array, I thought that is was posible to do that using just a pointer, thanks!
If you need string data, then use a string. Don't use char pointers/arrays. That's really the best solution here.

1
2
3
4
5
std::string p;
cin >> p;

myList.open( p.c_str() ); // <- use c_str() to "convert" the string to a const char*
    // when needed 


It's easier and much, much safer.
Ok Got it! I didnt know that, Thanks a lot!
Topic archived. No new replies allowed.