#include <iostream>
#include <fstream>
using namespace std;
int main() {
int k = 0;
int n;
int y[0];
cout << "write n\n";
cin >> n;
ifstream infile;
infile.open("xxx.in.txt");
infile >> y[0];
infile.close();
for(int x = 0; x < n; x++)
for(int j = 1; j < n; j++)
if(y[x] > y[j])
k = k++;
ofstream outfile;
outfile.open("xxx.out.txt");
outfile << k;
outfile.close();
}
filexxx.in contains two lines (it is a text file).
The first line has n amount of numbers, the second line has random numbers spaced apart.
I want to read from the second line.
How do I do this?
There are a few ways to get input from the second line of your text file.
If you know how long the first line is you could use istream::seekg.
ifstream infile;
infile.open("xxx.in.txt");
infile.seekg(length_of_first_line); // This would move the cursor to the second line.
// Code to read line 2.
If you do not know the value or it could change. Then you would need to use istream::getline and discard the first line.
char buffer[256];
ifstream infile;
infile.open("xxx.in.txt");
infile.getline(buffer, 256); // Read in the first line.
// Code to read line 2.
Input from text file:
With the use of <vector>, <fstream> and <sstream> you can use something along the lines of the following function:
using namespace std;
vector<vector<int> > getNumbers(string FileName) {
vector<vector<int> > Numbers; //Stores all the file's numbers
ifstream infile(FileName.c_str());
string String;
int a;
while (getline(infile, String)) {
vector<int> Line; //Stores each line's numbers
stringstream Stream(String);
while (Stream >> a) //Extracts numbers from 'Stream'
Line.push_back(a); //Each number is added to Line
Numbers.push_back(Line); //Each Line is added to Numbers
}
return Numbers;
}
It returns a two-dimensional vector of ints, where in getFileNumber[x][y] the x value is the line number (starting at value 0 for line 1), and the y value is the position of the number on the line (0 for the first number).
For example, in a file containing:
464 654334 35665 3456332 4454
2456 788654 3456 5775
The number 3456 would be getFileNumbers[1][2]
Output to another text file:
To copy the entire contents of the getFileNumbers vector to a text file, you'd do this:
std::vector<std::vector<int> > Numbers = getFileNumbers("xxx.in.txt");
std::ofstream Output("xxx.out.txt");
for (unsigned int y = 0; y < Numbers.size(); ++y) {
for (unsigned int x = 0; x < Numbers[y].size(); ++x)
Output << Numbers[y][x] << ' ';
Output << '\n';
}
Line specific output:
If you wanted to output line x of a file with std::cout, you'd do this:
std::vector<std::vector<int> > Numbers = getFileNumbers("xxx.in.txt");
for (unsigned int i = 0; i < Numbers[x].size(); ++i)
std::cout << Numbers[x][i] << ' ';
If you wanted to output line x to a file, you'd simply replace std::cout with a std::ofstream or std::fstream object.
Related
I have an input.txt file, I am trying to read input file by line and I want to compose 2 arrays. First line after space gives the size of the array. Size of the array is 3 for my example input file which is below. From second line after first space till end of the file composes array A[]. For this example A[3]={5,8,14} From Second line after second space till end of the input file composes content of array B[]. It is B[3]={67,46,23} for this input file. After first line first numbers of every line is just gives the line number of each line.Input file is like that:
10 3
1 5 67
2 8 46
3 14 23
Here is the below my start code. How can I get the second and last characters of a line for an input file?
#include<stdio.h>
#define N 128
#include <iostream>
#include <fstream>
int A[N];
int B[N];
int main(){
ifstream fin;
fin.open("input.txt", ios::in);
char CHARACTER;
int ITEMNUMBER = 0;
while (!fin.eof() ) {
fin.get(CHARACTER);
if (CHARACTER== '\n'){
++ITEMNUMBER;
}
}
printf("\n");
cout << "NUMBER OF ITEMS: " << ITEMNUMBER<< endl;
return 0;
}
You really need a solution with C-style arrays?
Or a solution with standard containers is good for you?
In this second case (that I suggest) I propose the following example
--- modified to load and print firstNum---
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stdexcept>
int main ()
{
std::ifstream fin("input.txt", std::ios::in);
int firstNum;
int unused;
unsigned dimV;
if ( ! (fin >> firstNum >> dimV) )
throw std::runtime_error("error reading dimension");
std::vector<int> a(dimV);
std::vector<int> b(dimV);
std::cout << "firstNum is " << firstNum << std::endl;
for ( unsigned i = 0U ; i < dimV ; ++i )
if ( ! (fin >> unused >> a[i] >> b[i]) )
throw std::runtime_error("error reading dimension");
for ( unsigned i = 0U ; i < dimV ; ++i )
std::cout << "-- " << a[i] << ", " << b[i] << std::endl;
return EXIT_SUCCESS;
}
The output
firstNum is 10
-- 5, 67
-- 8, 46
-- 14, 23
If the file remain consistent with the format you gave above and you do not reach the limit of the array, I think this will solve your problem.
int main(int argc, const char * argv[])
{
ifstream fin("input.txt", ios::in);
int A[N];
int B[N];
//get first num and size
int first; // not sure what that is for but i guess you know
int arraySize;
fin >> first;
fin >> arraySize;
int id;
int aData;
int bData;
int i = 0;
while(fin >> id >> aData >> bData)
{
A[i] = aData;
B[i] = bData;
i++;
}
return 0;
}
Would like to fill an array one line at a time from the file "Hello.cpp". However if I do it the way below I fill the entire file [w] times instead of just grabbing one line from the file for each iteration of i.
If I remove the { } from getline then the array is filled with the last line of "Hello.cpp" [w] times.
I am not sure how to get a new [i] each time from the Hello.cpp file.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int w=0;
ifstream in("Hello.cpp");
string s;
while(getline(in, s))
w=w+1; //first count the number of lines in the file for the array
string a[w];//make an array big enough for the file
for(int i = 0; i < w ; i++) {
ifstream in("Hello.cpp");
string s;
while(getline(in, s)){
a[i] = s;
cout << i + 1 << " " << s << endl;
}
}
I would close your file before reopening it (best practice).
Looks to me like you need to move your file open (ifstream constructor) outside of your for (do you really want to open the file w times)? Since you bother to count the lines first don't you really want something like this:
ifstream in1("Hello.cpp");
for(int i = 0; i < w ; i++) {
getline(in1, a[i]);
cout << i + 1 << " " << a[i] << endl;
}
I've been trying to grasp how reading and writing with the fstream class works, and I've become stuck. The program reads the magic number of the file correctly, and then suddenly fails to read an integer. I'm guessing I am missing something very obvious, but after several Internet searches, I've come up with nothing. If someone could point out what I'm missing, it would be extremely appreciated. Thanks!
#include <fstream>
#include <iostream>
#include "File.h"
using namespace std;
const char magicnumber[8] = {'C','H','S','R','L','I','N','E'};
const int magiclength = 8;
void saveLines(char* filename, int linenum, Line* lines){
//Create the file and write the magic number to it
ofstream file(filename, std::ios::trunc);
for(int kkk = 0; kkk < magiclength; kkk++)
file << magicnumber[kkk];
//Write the number of lines we expect
file << linenum;
//Write the lines' data
for(int iii = 0; iii < linenum; iii++){
file << lines[iii].start.x << lines[iii].start.y;
file << lines[iii].finish.x << lines[iii].finish.y;
file << lines[iii].thickness;
}
cout << linenum << endl;
file.close();
}
Line* openLines(char* filename){
ifstream file(filename);
if(!file.is_open())
return NULL;
//Read the magic number of the file
char testnumber[12];
for(int jjj = 0; jjj < magiclength; jjj++)
file >> testnumber[jjj];
//Make sure the file contains the right magic number
for(int iii = 0; iii < magiclength; iii++){
if(testnumber[iii] != magicnumber[iii])
return NULL;
}
//Get the number of lines
int linenum = -1;
file >> linenum;
cout << linenum << endl;
if(linenum <= 0 || file.fail())
return NULL;
Line* product = new Line[linenum];
for(int kkk = 0; kkk < linenum; kkk++){
file >> product[kkk].start.x >> product[kkk].start.y;
file >> product[kkk].finish.x >> product[kkk].finish.y;
file >> product[kkk].thickness;
}
file.close();
return product;
}
In the openLines() function, the file opens correctly, and the magic number is read and matched correctly, but when the variable "linenum" is read, the file reads as gibberish, the fail() flag turns true, and the function returns NULL. If it matters, here's the Line struct:
typedef struct{
int x, y;
} Point;
typedef struct{
float slope;
float thickness;
Point start;
Point finish;
bool defined;
} Line;
I am using SDL in this project. I do not know if this matters, but I'm including it for completeness' sake. In cout.txt I get 2 (For the linenum when I'm writing the file) and then 2147483647 when I read it back. Thanks for looking!
I created a text file love.txt:
i love you
you love me
How do I store them into separate array, namely line1 and line2 and then display them out in console?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1[30];
string line2[30];
ifstream myfile("love.txt");
int a = 0;
int b = 0;
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
while(!myfile.eof())
{
getline(myfile,line1[a],' ');
cout<<"1."<<line1[a]<<"\n";
getline(myfile,line2[b],' ');
cout<<"2."<<line2[b]<<"\n";
}
}
Try specifying the last argument as '\n' in both getline() functions:
getline(myfile, line1[a], '\n');
instead of
getline(myfile, line1[a], ' ');
How about this.. .
vector <string> v;
string line;
ifstream fin("love.txt");
while(getline(fin,line)){
v.push_back(line);
}
You can think of a string as an array of characters, so you will only need one array of strings:
const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
getline(myfile,line[i]); // read the next line into the next string
++i;
}
for (i=0; i < SIZE; ++i) {
if (!line[i].empty()) { // print only if there is something in the current line
cout << i << ". " << line[i];
}
}
You could maintain a counter to see how many lines you have stored into (instead of checking for empty lines) as well -- this way you will properly print empty lines as well:
const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
getline(myfile,line[i]); // read the next line into the next string
++i;
}
size_t numLines = i;
for (i=0; i < numLines; ++i) {
cout << i << ". " << line[i]; // no need to test for empty lines any more
}
Note: you will be able to store only up to SIZE lines. If you need more, you will have to increase SIZE in the code. Later on you will learn about std::vector<> that allows you to dynamically grow the size as needed (so you won't need to keep track of how many you stored).
Note: the use of constants like SIZE allows you to change the size in one place only
Note: you should add a check for errors in the input stream on top of eof(): in case there was a read failure other than reaching the end of the file:
while (myfile && ...) {
// ...
}
here myfile is converted to a boolean value indicating if it is OK to use it (true) or not (false)
Update:
I just realized what you are after: you want to read the input as series of words (separated by space), but display them as lines. In this case, you will need arrays-of-arrays to store each line
string line[SIZE1][SIZE2];
where SIZE1 is the maximum amount of lines you can store and SIZE2 is the maximum amount of words you can store per line
Filling this matrix will be more complex: you will need to read the input line-by-line then separate the words within the line:
string tmp; // temporary string to store the line-as-string
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able to extract
// the words
size_t j=0; // the current word index
while (ss) {
ss >> line[i][j]; // here i is as above: the current line index
++j;
}
Output:
for (i=0; i < numLines; ++i) {
cout << i << ". ";
for (size_t j=0; j < SIZE2; ++j) {
if (!line[i][j].empty()) {
cout << line[i][j] << " ";
}
}
}
My complete solution.
the config.txt file contains:
#URL WEB POP3 IMAP SMTP FTP DNS PING ORDER
st-xxxx.com 1 1 0 1 1 0 1 1
24.xxx.195.11 1 1 0 1 1 0 1 2
24.xxx.195.12 1 1 0 1 1 0 1 3
192.168.0.100 1 1 0 1 1 0 1 4
and my code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream myfile("config.txt");
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
const size_t SIZE1 = 30;
const size_t SIZE2 = 10;
string line[SIZE1][SIZE2];
string tmp; // temporary string to store the line-as-string
size_t i=0; // the current line index
size_t j=0; // the current word index
while(!myfile.eof() && i < SIZE1) {
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able
//to extract the words
size_t j=0;
while (ss) {
ss >> line[i][j]; // here i is as above: the current line index
++j;
}
i++;
}
size_t numLines = i;
cout << numLines << "\n";
for (i=1; i <= numLines; ++i) {
for (size_t j=0; j < SIZE2; ++j) {
if (!line[i][j].empty()) {
cout << line[i][j] << " ";
}
}
cout << "\n";
}
cout << line[3][0] << "\n"; // print the third line first word
}
Hope tht helps anybody who is searching for this type of solution, even if the post is quite old.
I ve got a txt file with double matrix 50x8. The first two lines contains the array size
50
8
the 50x8 matrix. When i trid to read this file with the above code:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("C:/Users/zenitis/Desktop/BTHAI_2.3b-src/BTHAI/txtFiles/W1.txt");
double events[50][8];
while (!infile.eof())
{
for(int j=0;j<50;j++)
{
for(int k=0; k<8;k++)
{
infile >> events[j][k];
// infile.get(c
}
}
} //end while
infile.close();
for(int i = 0; i<50; i++){
for(int l=0; l<8; l++){
cout << events[i][l] << " ";
}
cout << "\n";
}
cout << events[0][0];
system("pause");
return 0;
}
Firstly when i print the results the first two elements of the events matrix are the last two of the file. Secondly any idea how to read just the two first elements which is in fact the size of the matrix????
You read the number of rows and columns like this:
int R, C;
infile >> R;
infile >> C;
You do it before the nested loops that read the rest of the file. Then you use the numbers from the file as your end-of-loop targets, rather than hard-coding 50 and 8.