I want to get lines from a .txt file and save it into an array. Then I want to display it in a for loop. Here is my code and I don't know what is wrong with it. My file is named quiz.
The program is running but it doesn't display array with lines.
#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main()
{
fstream quiz;
quiz.open("quiz.txt", ios::in);
if(quiz.good()==false)
{
cout<<"File does not exist"; exit(0);
}
string array[100000];
string one;
int counter=0;
while(getline(quiz,one))
{
one=array[counter];
counter++;
}
for(int i=0; i<=counter; i++)
{
cout<<array[i];
}
quiz.close();
return 0;
}
Related
hi I am trying to read a specific line from a text file update that and put it back to the same line without affecting the other lines in c++
here I am trying to execute the code and values get added when I re-execute it
#include <iostream>
#include <stream>
#include <stdio.h>
#include <string>
#include <stream>
using namespace std;
void stringGen(char num){
ifstream ifile;
ifile.open("example1.txt");
if(ifile) {
int LINE = 5;
string line;
ifstream myfile1 ("example1.txt");
for (int i = 1; i <= LINE; i++)
getline(myfile1, line);
cout << line<<endl;
stringstream geek(line);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
ofstream MyFile("example1.txt");//
MyFile.close();
}
else{
num=61001;
ofstream MyFile("example1.txt");//
MyFile << num;
MyFile.close();
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("example1.txt");//
MyFile << num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
At first, you need to understand, how files, with lines are stored. Simplified, it is a sequence of bytes, one byte after the other. There maybe some special characters in this byte sequence, which people can interprete as the end of a line, e.g. '\n'. But also other characters or even more than one character is possible:
If you look at the following text.
Hello1
World1
Hello2
World2
it maybe stored in a file like this:
Hello1\nWorld1\nHello2\nWorld2\n
And just because we interprete a '\n' as the end of the line, we can "see" lines in there.
So, if you want to modify a line, then you would need to find the start position of the thing that we interprete as a line in the file, and then modify some bytes.
That can of course only be done, if the length of the "line" will not change. Then you could use "seek" functions and overwrite the needed bytes.
In reality, nobody would do that. Normally, you would read "lines" of the file into some kind of memory buffer, then do the modification there and then write back all lines.
For example, you would define a std::vector and then read all lines, by using std::getline and push_back the lines in the std::vector.
The modifications will be done in the std::vector, and the all data will be written back to the file, overwriting all "old" data.
There are more answers to this question. If you have any more specific question, I will answer again
Some simple example code
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
// Here we will store all lines of the text file
std::vector<std::string> lines{};
// Open the text file for reading and check, if it could be opened
if (std::ifstream textfileStream{ "test.txt" }; textfileStream) {
// Read all lines into our vector
std::string oneLine{};
while (std::getline(textfileStream, oneLine)) {
// Add the just read line to our vector
lines.push_back(oneLine);
}
// For test purposes, modify the first line
if (not lines.empty()) lines[0] = "MODIFIED";
}
else std::cerr << "\nError: Could not open input text file\n";
// Write back data
// Open the text file for writing and check, if it could be opened
if (std::ofstream textfileStream{ "r:\\test.txt" }; textfileStream) {
// Iterate over all lines and wriite to file
for (const std::string& oneLine : lines)
textfileStream << oneLine << '\n';
}
else std::cerr << "\nError: Could not open output text file\n";
return 0;
}
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
void stringGen(char num){
int count=0;
int a;
string line,check,linex;
string msg="Message_Handler:";
fstream ifile;
ifile.open("sample.txt",ios::in|ios::out);
if(ifile){
while(getline (ifile,line)) {
if (line.find("Message_Handler:") == 0){
check=line.substr(16,5);
count++;
a=ifile.tellp();
}
}
ifile.close();
if(count==0){
int num=61001;
cout<<num<<endl;
num=num+1;
ofstream examplefile ("sample.txt",ios::app);
examplefile<<"Message_Handler:"<<num;
examplefile.close();
}
if(count==1){
cout<<check<<endl;
stringstream geek(check);
int num=0;
geek>>num;
if(num<61004){
num=num+1;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
else{
int num=61001;
stringstream ss;
ss << num;
string nums = ss.str();
fstream MyFile("sample.txt",ios::in|ios::out);
MyFile.seekp(a-5);
MyFile<<nums;
}
}
}
else{
int num=61001;
cout<<num<<endl;
ofstream MyFile("sample.txt",ios::app);
MyFile <<"Message_Handler:"<< num+1;
MyFile.close();
}
}
int main (){
char num;
stringGen(num);
return 0;
}
Yes, this is a question for a class, but I don't want my homework done for me. I just need to figure out where I'm going wrong. The question that I have to figure out states this:
Write a program which uses the file produced in Lab 1 as its input file. This program gets user input of a value from 1000 to 10000, and counts how many times the user's value appears in the input file. It reports to the user using screen output.
Here's the code that I have after several failed attempts:
#include <iostream>
#include <fstream>
using namespace std;
int count(int number, int input, int length)
{
int counter = 0;
for(int i = 0; i < length; i++)
if(input == number)
counter++;
return counter;
}
int main()
{
int num,input;
ifstream fin;
fin.open("ran_num.txt");
if(fin.fail())
{
cout<<"Input file opening failed."<<endl;
cin.get();
}
cout<<"Enter a number between 1000 to 10000:";
cin>>num;
fin>>input;
cout<<num<<"appears "<<count(num, input, 3000)<<" times in the file."<<endl;
return 0;
}
I'm completely lost and just need to figure out what I use to count a user inputer value. Any help is appreciated!
Edit
This is what I have now. My program can now read the whole file, but I still do not know how to count a user-inputted number.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream fin("ran_num.txt");
int num, user_input;
cout<<"Enter a number between 1000 to 10000:";
cin>>user_input;
while(fin>>num)
{
if(num == user_input)
{
cout<<count++;
}
}
return 0;
}
Are you sure your program is opening the file?
You should check if the file is opened correctly, you also should close the file after use.
Also you're outputting count before incrementing it.
I suggest changing your while loop this way:
if (fin.is_open())
{
while (fin >> num)
{
if (num == user_input)
{
++count;
}
}
fin.close();
cout << count;
}
else
{
cout << "Unable to open file";
}
This is the correct code that I have. It works perfectly now thank you!
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream fin("ran_num.txt");
int num, user_input, count;
cout<<"Please enter a number from 1000 to 10000:";
cin>>user_input;
if (fin.is_open())
{
while (fin >> num)
{
if (num == user_input)
{
++count;
}
}
fin.close();
cout<<user_input<<" occurs "<<count<<" times.";
}
else
{
cout<<"Unable to open file.";
}
fin.close();
return 0;
}
I was able to finally produce a working code on inputting and displaying n student details (Student ID#, Name and Age)... although the name is not full name capable, I would like to write these inputs to a text file and then read from text file also. I will appreciate any help, please:
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>
using namespace std;
struct student
{
int sno, sage;
char sname[100];
};
int main(int e, char* argv[])
{
struct student s[e];
int i;
ofstream outfile;
outfile.open("info.txt");
printf("How many entries are you making?: ");
scanf("%d",&e);
printf(" \n");
printf("Please enter Student Information:\n");
for(i=0;i<e;++i)
{
s[i].sno=i+1;
printf("\nEnter Information for student %d\n",s[i]);
printf("================================\n");
cout<<"\nEnter (4 digits) student ID No: ";
cin>>s[i].sno;
cout<<"\nEnter student's name: ";
cin>>s[i].sname;
cout<<"\nAge of student: ";
cin>>s[i].sage;
printf("\n");
//If i do this, I get only first set of data
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
/*I am trying to get data into txt file using the loop below but it looks odd and it collects some of the first set of data, and completes it like this: 1212 kop 23
1627953384 1629646589*/
/*for(i=0;i<e;++i)
{
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}*/
outfile.close();
}
printf("Displaying information of student(s):\n");
printf("==================================\n");
for(i=0;i<e;++i)
{
printf("\nInformation for Student %d:\n",i+1);
cout<<"\nStudent ID:"<<s[i].sno;
cout<<"\nStudent name: "<<s[i].sname;
cout<<"\nAge of student: "<<s[i].sage;
printf("\n\n");
}
return 0;
}
I suggest starting with a simple program that writes to a file:
#include <fstream>
#include <iostream>
#include <cstdlib>
int main(void)
{
std::ofstream output_file("text.txt");
std::cout << "Writing to output file.\n";
output_file << "This is my text.\n";
output_file.flush();
std::cout << "Finished writing to file.\n";
output_file.close();
std::cout << "Paused. Press Enter to continue.\n";
std::cin.ignore(100000, '\n');
return EXIT_SUCCESS;
}
After executing the above program, you should verify that the text file contains the correct text.
Next, you can add other code, such as prompting the User and obtaining the input.
I think you don't know how to read or write through file. That's why you are having problem. There are two ways which people generally use. Go through these two sample tutorial for good understanding of these methods.
- c methods
- c++ methods
This is your code which I've modified to read and write from files using both methods -
Given Input file - student.txt. //first line No. of input
2
1234 manish 34
4321 mukesh 43
Code
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
struct student
{
int sno, sage;
char sname[50];
};
//Read data using C Method
void ReadAndWriteCMethod(){
student s[100];
FILE* f;
f = fopen("student.txt","r");
int N;
fscanf(f,"%d",&N);
**//Reading from file**
for(int i=0; i<N; i++){
fscanf(f,"%d %s %d",&s[i].sno, &s[i].sname, &s[i].sage);
}
fclose(f);
**//Writing over file**
f = fopen("wstudent1.txt","w+");
for(int i=0; i<N; i++){
cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
fprintf(f,"%d %s %d\n",s[i].sno,s[i].sname,s[i].sage);
}
fclose(f);
}
//Reading and writing using C++
void ReadAndWriteCPlusPlusMethod(){
student s[100];
**// Reading data**
std::ifstream fin("student.txt");
char s2[100];
int N; fin>>N;
for(int i=0; i<N; i++){
fin>>s[i].sno>>s[i].sname>>s[i].sage;
cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}
fin.close();
**//Writing data**
std::ofstream fout("wstudent2.txt");
for(int i=0; i<N; i++){
fout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}
fout.close();
}
int main()
{
ReadAndWriteCMethod();
ReadAndWriteCPlusPlusMethod();
}
After running, this will generate two files wstudent1.txt and wstudent2.txt files.
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
string arr[3][2];
int i =0,j=0;
ofstream out ("test1.dat" , ios::app);
string name;
while(true)
{
cin>>name;
if(name=="end")
break;
out << name <<' ' ;
}
out.close();
ifstream in ("test1.dat", ios::in);
in >> name;
while(!in.eof())
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}
in.close();
for(i=0;i<3;i++){
cout<<endl;
for(j=0;j<2;j++){
cout<<arr[i][j]<<" ";}
}
return 0;
}
please help i have run-time error with this.what is my problem?i want to write some data in a file then read them and put them in an array and then print the array.i want to write and read the file by string not by character.sorry about my weak english.
thanks
Try adding a condition for i in your while loop.
This fixes your run-time error with the array bounds but you still have a logic error (unless you want duplicate occurrences of the same word in your array?)
while(!in.eof() && i < 3)
{
arr[i][j]=name;
in>>name;
j++;
arr[i][j]=name;
i++;
j=0;
}
I am trying to count the number of lines in a text file but each time i'm running this code i am getting 1987121509 as the number of lines. Can you please tell me how i can modify my code to get the correct number of lines? Thank you.
Here's the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine;
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine; //increment numLine each time a line is found
}
cout<<"\nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}
Here's the correct code(I found out after asking the question)
Silly mistake of not initializing the variable correctly.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine = 0; //didn't set it to zero.
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine;
}
cout<<"\nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}