How to Read and Process Char+Number Data in C++ from a Text File?

  • Comp Sci
  • Thread starter Joon
  • Start date
  • Tags
    C++
In summary: Get the length of the triangle length = inFile >> ch >> x1 >> y1 >> z1; //Calculate the area area = total_length * side12 + total_length * side13 + total_length * side23; //Write the results to the standard output cout << "The length of the triangle is " << length << " meters. The area is " << area << endl;
  • #1
Joon
85
2
Hello, the text file I'm trying to read is formatted as below:

C:
                             x                                y                                  z
point1                  number                 number                           number
I have used getline to discard the first line, the header.
What I'm wondering is that after I read the file with ifstream then wrote the code as inFile >> char >> x1 >> y1 >> z1 , then calculated something using x1,y1,z1, the output gives a weird number. I think it is because of point1 which is char + number, how should I set point1 as character then read it with the code above?
 
Last edited:
Physics news on Phys.org
  • #2
Joon said:
Hello, the text file I'm trying to read is formatted as below:

C:
                             x                                y                                  z
point1                  number                 number                           number
I have used getline to discard the first line, the header.
What I'm wondering is that after I read the file with ifstream then wrote the code as inFile >> char >> x1 >> y1 >> z1 , then calculated something using x1,y1,z1, the output gives a weird number. I think it is because of point1 which is char + number, how should I set point1 as character then read it with the code above?
As you have described it, point1 is a character string, not a character. You'll need to use a char array or string to hold that particular item. It would help if you showed the code you're using. You don't need to post the whole program -- just the loop you're using and the declarations for the variables.
 
  • Like
Likes Joon
  • #3
Thank you, below is the whole code. I'm trying to compute the total length of a 3D triangle and its area.
I'm using file output. Using char string, should I change char c; in the code below to char str[6]?

C:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void foutput(double length, double area);

int main() {

    
    double total_length, area, x1, x2, x3, y1, y2, y3, z1, z2, z3, side12, side13, side23, halfparameter;
    

    ifstream inFile("triangle_cw2(1).txt");
    string line, c;
    char c;

    if (inFile.is_open()) {
        getline(inFile, line);
    }

    inFile >> ch >> x1 >> y1 >> z1;
    inFile >> ch >> x2 >> y2 >> z2;
    inFile >> ch >> x3 >> y3 >> z3;

    
    total_length = 0;
    area = 0;

        total_length = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1))+ sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1)+(z3-z1)*(z3-z1)) + sqrt((x3-x2)*(x3-x2)+ (y3-y2)*(y3-y2) + (z3-z2)*(z3-z2));
        side12 = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1) + (z2 - z1)*(z2 - z1));
        side13 = sqrt((x3 - x1)*(x3 - x1) + (y3 - y1)*(y3 - y1) + (z3 - z1)*(z3 - z1));
        side23 = sqrt((x3 - x2)*(x3 - x2) + (y3 - y2)*(y3 - y2) + (z3 - z2)*(z3 - z2));
        halfparameter = (side12 + side13 + side23) / 2;
        area = sqrt(halfparameter* (halfparameter - side12) * (halfparameter - side13) * (halfparameter - side23));
            
        
        foutput(total_length, area); // You must use this function for output. 
    inFile.close();
    

    // Do not use system("pause") for this task
    
    return 0;
}

////////  Do not change this function and must use this funtion for output.  /////
void foutput(double total_length, double area) {

    ofstream cw2task1output;
    cw2task1output.open("cw2task1output.txt");

    cw2task1output << "The total length of sides = " << total_length << endl;
    cw2task1output << "The area of triangle = " << area << endl;

    cw2task1output.close();
}
 
  • #4
joon said:
C:
string line, c;
    char c;

    if (inFile.is_open()) {
        getline(inFile, line);
    }

    inFile >> ch >> x1 >> y1 >> z1;
    inFile >> ch >> x2 >> y2 >> z2;
    inFile >> ch >> x3 >> y3 >> z3;
This code won't compile -- you have declared c twice. No doubt you meant the second declaration to be for 'ch' .
Even with that fix, things won't work. The first item read from a line needs to be a string, not a single character. You need to declare a string variable to pick up the the name of the point. Is it something like P123 in the text file?
 
  • #5
The text file looks like below. Sorry for the mistake, I didn't notice I declared c twice.

C:
                             x                                y                                  z
point1                  number                 number                           number
point2                  number                 number                           number
point3                  number                 number                           number
Would the code work if I declare string ch; ? Ch string[6]?
 
  • #6
Joon said:
The text file looks like below. Sorry for the mistake, I didn't notice I declared c twice.

C:
                             x                                y                                  z
point1                  number                 number                           number
point2                  number                 number                           number
point3                  number                 number                           number
Would the code work if I declare string ch; ? Ch string[6]?
This one -- string ch; -- but give it a different name, like pointName. If you call it ch, that suggests it's just one character, which it isn't.
 
  • #7
I have declared as string pointname; but it does not change anything.
 
  • #8
Is this what your code looks like?
C:
inFile >> pointname >> x1 >> y1 >> z1;
After this line executes (in the debugger), what is stored in pointname? Is the input operation storing the whole line into pointname?

If it's doing that, you might want to consider using an input function with more control over what gets read for that first item, as in the following:

C:
inFile.read(pointname, 6);
This would read 6 characters from the file, and store them in pointname. For additional data on the line, you could use the stream extraction operator (>>) like you were doing, but just for the three numeric items.

Also, your code has a bug.
Code:
if (inFile.is_open()) { 
       getline(inFile, line);    } 
inFile >> ch >> x1 >> y1 >> z1;
...
This works if the file is successfully opened, but what happens if the file can't be opened? It will attempt to read from a file that doesn't exist or can't be opened for some reason, and will throw an exception.
 
  • #9
Yes that's what my code looks like. I'm not sure about what's stored in pointname. After I run the debugger, the values of total length and area are shown in the output file.
I think it might be because of the spaces between x1 , y1 and z1, what do you think?
 
  • #10
Joon said:
I'm not sure about what's stored in pointname.
Are you using a debugger? If so, you should be able to see the values of all local variables. If you're not using a debugger (you really should be!), insert an output statement to see what's in pointname.

C:
inFile.read(pointname, 6);
cout << "pointname: " << pointname << endl;
inFile >> x1 >> y1 >> z1;
You can delete the 2nd line above once you know what's being read.

Joon said:
After I run the debugger, the values of total length and area are shown in the output file.
I think it might be because of the spaces between x1 , y1 and z1, what do you think?
I don't think the spaces will make a difference, provided that you can read in (and discard) the name of the point. The extraction operator will ignore leading spaces when you're inputting to a numeric variable, and will stop once it hits a space character.
 
  • #11
It says the pointname in inFile.read(pointname, 6) is char* and I declared it to be string. Should I declare it as something else then?
 
  • #12
"It says..." - who says that? Does the output statement in my example display what's in pointname?
 
  • #13
When I run the debugger, it doesn't work (error) due to the reason stated above. The pointname in the inFile.read bracket is underlined in red and the debugger won't open.
 
  • #14
See if this works -- different declaration for pointname.
C:
char pointname[8];
Everything else the same.
 
  • #15
No, on the output screen, it only returns pointname: point 1 then after that some weird characters.
I'll try figure out what the problem is and let you know.
 
  • #16
I took some of your code from post #1 and created a short program, but with a couple of minor changes. The code works as expected, with no problems. The purpose of the example here was to test whether the program is correctly extracting the point name and three numbers on each line.
C:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//void foutput(double length, double area);

int main() 
{ 
    double total_length, area, x1, x2, x3, y1, y2, y3, z1, z2, z3;
    ifstream inFile("Input.txt");
    string line, ptName; 

   if (inFile.is_open()) {
       getline(inFile, line);
       inFile >> ptName >> x1 >> y1 >> z1;
       inFile >> ptName >> x2 >> y2 >> z2;
       inFile >> ptName >> x3 >> y3 >> z3;
   }
  // total_length = 0;
  //area = 0;
  inFile.close();
 
   return 0;
}
I also created an input file, Input.txt, that looks like this:
Code:
    x    y   z
point1 1.1 2.2 3.3
point2  2.2 3.3 4.4
point3  3.3  4.4 5.5

The input file has the header line that starts with a tab character, and with spaces between x, y, and z. The other three lines have a string of characters for the point name, followed by a space, and the three decimal numbers that are separated by one or more spaces. Tabs would also work.

After each inFile >> line executes, ptName contains the name of the point, and the xn, yn, and zn variables each contain the appropriate value.

I don't know why you are having trouble with your code.
 
  • #17
Yes I fixed the code a few hours ago exactly same as yours and it worked! The only problem was that I didn't declare pointnumber as string and that the file where the output text shows was not the right file(it's the same file but weirdly it didn't work when I attached it to resource file and then write the code whereas it worked when I attached it after I wrote the code). Thank you for your help.
 

1. How do I read a character and a number in C++?

To read a character and a number in C++, you can use the cin function. For the character, you can use the get() function and for the number, you can use the >> operator. For example, char ch = cin.get(); and int num; cin >> num;

2. How do I convert a character to its corresponding ASCII value in C++?

In C++, you can use the int() function to convert a character to its corresponding ASCII value. For example, char ch = 'A'; int ascii = int(ch); will assign the ASCII value of 'A' (65) to the variable ascii.

3. How do I read multiple characters in C++?

You can use the getline() function to read multiple characters in C++. This function takes in two parameters - the input stream (such as cin) and the character array to store the input. For example, char str[20]; getline(cin, str); will read in a string of maximum 20 characters from the user.

4. How do I read a specific character from a string in C++?

To read a specific character from a string in C++, you can use the at() function. This function takes in the index of the character you want to access as a parameter and returns the character at that index. For example, string str = "Hello"; char ch = str.at(1); will assign the character 'e' to the variable ch.

5. How do I read a character until a specific condition is met in C++?

You can use a while loop to read a character until a specific condition is met in C++. For example, char ch; while (ch != 'q') { // read character and perform desired operations } will continue to read characters until the user enters 'q'.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
14
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
23
Views
7K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
Back
Top