Reading text file

Discussion in 'C++' started by griff91, Jul 14, 2020.

Tags:
  1. griff91

    griff91 New Member

    Joined:
    Jul 13, 2020
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    1
    I am new to programming in C++ but I am currently trying to read a text file and then wanting to print it in the console. The text file is 500x2 where the first column is r and the second column is theta. When I build and run the program it. In the console, I would like it to print the values exactly how it is shown in the text file, that is:

    0.005 3.1485
    0.005 6.1749
    etc.

    Instead the data is printed out like this:
    0.005 0.005
    3.1485 3.1485
    0.005 0.005
    6.1749 6.1749


    I have attached my code below and any help would be greatly appreciated.

    Code:
    #include <vector>
    #include <fstream>
    #include <iostream>
    int M = 500;
    int main(){
    std::ifstream myFile;            //creates stream myFile
     myFile.open("random_cylind.txt");  //opens .txt file
    
    std::vector<double>r;  //vector to store the numerical values in
    std::vector<double>theta;
    double number = 0 ;
    while(myFile >> number){   
        r.push_back(number);
        theta.push_back(number);
    }
    for (int i = 0; i < r.size(); i++){
        std::cout << r[i] << theta[i] << std::endl;
            }
        return 0;
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice