简体   繁体   中英

How do I copy the string in a txt file?

Here is an example of text file I am dealing with:

http://example.com/object1 50 0
http://example.com/object2 25 1
http://example.another.com/repo/objects/1 250 0
ftp://ftpserver.abc.edu:8080 13 5
...

I want to pass the url, size(the first number), and the priority(the second number) into array. Here is my code:

ifstream infile;
infile.open("ece150-proj2-input.txt");

//Get the number of lines in the text file
int lines = 0;
while (!infile.eof()) {
    string line;
    getline(infile, line);
    lines++;
}

//Get the components in the input file
char url[lines][50];
float size[lines];
float delay[lines];
for (int i = 0; i < lines; i++) {
    infile >> url[i] >> size[i] >> delay[i];
}

//Testing if I get the url address correctly
cout << url[0] << endl;
cout << url[1] << endl;

However the result are some strange character:

pĞQ?
?Q?

Why is this happen? Can anyone solve this problem. Thank you ;-)

The issue here is that when you read through the file once the stream is now at the end of the file. You need to either call infile.seekg(0, infile.beg); to rewind to the beginning of the stream. You could also close and reopen infile.

Secondly you are declaring char url[lines][50]; You can not do this. The length of arrays in c++ must be compile time constants. I'm actually surprised your code compiled and gave you any output at all.

I would recommend that you use std::vector which is like an array but you can add elements to the end. That way you do not need to know the number of lines before hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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