This question already has answers here:
Can't open file for input C++
(1 answer)
Cannot open file with relative path? (C++ ifstream)
(1 answer)
Closed 2 years ago.
I have a .txt file containing a list of about 200 numbers with one on each line and I'm trying to parse it with C++ but I'm facing some issues -- here's my code:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
ifstream file;
file.open("input.txt");
// check for error
if(file.good())
cout << "opened!";
else
{
cerr << "issue" << endl;
exit(1);
}
while (file >> n)
{
cout << n;
}
file.close();
}
Basically I'm trying to input these elements into an integer array (separate from this) but I have trouble reading the .txt file for some reason as it always results in "issue". Also, when I try for example to output multiple numbers from this file
int a,b,c;
file >> a >> b >> c;
cout << a << b << c ;
it always results in (seemingly) random numbers being printed. I thought it was a problem with the location of my input file but after recreating a project and changing the locations of my files I still can't seem to fix this. How can I solve this issue?
Related
I am trying to read a .txt file with some floats into my code.
I wrote a sample code just to tackle the issue outside my main code and I am using the following floats to test it:
10.8f
100.8f
-10.8f
The issue I am running into is that the code only reads in the first float properly and displays it but all the other floats following it do not look correct:
10.8
0
4.57874e-41
Code:
#include<fstream>
#include<iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
float Cam1,Cam2,Cam3;
string path = "sample.txt"; //Text file with above mentioned floats
ifstream fin;
fin.open(path);
if(fin.is_open())
{
fin >> Cam1;
fin >> Cam2;
fin >> Cam3;
fin.close();
}
cout << Cam1 << '\n';
cout << Cam2 << '\n';
cout << Cam3 << '\n';
}
I really am confused as to why it reads the first properly but not the others, it works when I change the values as well, the above is just one example case. I am fairly new to C++ so any help would be greatly appreciated thank you!
The f suffix is valid in C++ code, but not in input text parsed by istream. It's useful in code to distinguish between float and double constants, but user input doesn't control variable data types.
I have been working on this for past 2 days and I not able to do anything on this.
Scenario: This is on Linux machine RHEL7 which has c++98
I am trying to read a text file and using vector I am storing all the contents in the text file line by line into the vector and find a string using vector. If the string matches, one block of codes executes, and if it doesn't the other block executes. The problem is I am not able to find if it read the file or not and if it reads the file then find login of vector doesn't work I guess. Every time I execute, it goes into to else block.
This is my piece of code-->It works fine in windows and doesn't work in Linux.
#include <iostream>
#include <fstream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main()
{
string user;
cout << "enter user" << endl;
cin >> user;
std::string userappend = "user,";
userappend.append(user);
userappend.append(",I");
string myText;
vector<string> v;
ifstream MyReadFile("//etc//foldername//users.txt");
while (getline(MyReadFile, myText))
v.push_back(myText);
if (std::find(v.begin(), v.end(), userappend) != v.end())
{
std::cout << "if block";
std::cout << "Current User : " << userappend << endl
<< endl;
}
else
{
cout << "nothing" << endl;
}
MyReadFile.close();
return 0;
}
Note: I am trying to create a dll file and .so file and dll works fine with this logic. After generating .so file, the string find logic or reading file logic is not working in linux. Please Help ME
Is there anyone could help me to check where I did wrong? Or explain why? I am a beginner and I tried my best to open the binary file. But it just runs out "file is open" "0". Nothing came out.
The objective:
The Count3s program opens a binary file containing 32-bit integers (ints). Your program will count the number of occurrences of the value 3 in this file of numbers. Your objective is to learn about opening and accessing files and apply your knowledge of control structures. The name of the file containing data used by the program is "threesData.bin".
my code as below, please help me if you know it. Thank you in advance!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int count=0 ;
ifstream myfile;
myfile.open( "threesData.bin", ios::in | ios :: binary | ios::ate);
if (myfile)
{
cout << "file is open " << endl;
cout << count << endl; }
else
cout << "cannot open it" << endl;
return 0;
}
First of all you should read from file opened in binary mode with
myfile.read (buffer,length);
where buffer should be defined as
int data;
and used as
myfile.read (&data,sizeof(int));
The second important point is reading from file for more than one number - you need loop that is controled by condition that check stream. For example:
while (myfile.good() && !myfile.eof())
{
// read data
// then check and count value
}
And the last thing, you should close file, that was successfully oppened, after you finished reading:
myfile.open( "threesData.bin", ios::binary);
if (myfile)
{
while (myfile.good() && !myfile.eof())
{
// read data
// then check and count value
}
myfile.close();
// output results
}
And some additinal tips:
1) int is not always 32-bit type, so consider using int32_t from <cstdint>; and if your data has more than 1 byte, may be byte order is important, but it was not mentioned in the task description
2) read allows reading more than one data object per one call, but in that case you should read to array instead of one variable
3) read and try examples from references and other available resources like this.
I am writing a small program to just get the lines from a srt file in a specific format. However I am getting a garbage value in the very first (and only that) read I do using getline. Can someone point out why am I getting this abnormal behaviour?
//Small program to get the text from the srt files.
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<vector>
#include<sstream>
#include<conio.h>
using namespace std;
void srtToTranscript(ifstream* iFile, ofstream *oFile);
int main(){
std::string file_name;
std::string transcript;
cout << "Enter srt file name (without extension)";
cin >> file_name;
ifstream iFile;
ofstream oFile;
iFile.clear();
iFile.open("data\\" + file_name+".srt");
oFile.open("data\\" + file_name + "_result.txt");
srtToTranscript(&iFile,&oFile);
cout << "Conversion done. Check in the same folder";
cout << "Press a key to exit... ";
while (!_kbhit());
char dummy = _getch();
return 0;
}
void srtToTranscript(ifstream* iFile, ofstream* oFile)
{
int i = 1;
std:string line;
for (; getline(*iFile, line);)
{
cout << line << endl;
cout << to_string(i) << endl;
if (line.compare(to_string(i)) == 0){
getline(*iFile, line);
i++;
continue;
}
*oFile << line + ",\n";
}
oFile->close();
}
appended is a sample of the file I am reading from:
1
00:00:00,000 --> 00:00:12,000
Translator: Thu-Huong Ha
2
00:00:12,038 --> 00:00:15,012
Over the last two decades, India has become
The problem is your ifile is not being opened successfully.
I'm seeing #include <conio.h> in your include list so I assume that you are working on Visual Studio? If you have use the default directory structure when setting up Visual Studio, then say that you have a project named: "Foo" Your .srt file needs to go here:
.../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo.srt
When I correctly placed the file there and at the prompt I entered:
Foo
I got this output in: ".../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo_result.txt":
00:00:00,000 --> 00:00:12,000,
,
Translator: Thu-Huong Ha,
,
00:00:12,038 --> 00:00:15,012,
,
Over the last two decades, India has become,
One thing I'd make sure of is that your line declaration in srtToTranscript is defined:
string line
Not:
std:string line
This question already has an answer here:
Cannot open input file
(1 answer)
Closed 7 years ago.
I am trying to create a program that asks the user for the name of a file, then opens the file, adds the sum of all the integers listed on the file, then writes that sum on an output file.
After writing my code and saving the testfile1.txt into the same folder as the program, the program keeps giving me the: "could not access testfile1" (message I output to notify myself that it is unable to open the testfile1.txt).
Here is what I have so far (skipped the lines with description blocks):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream inputFile;
ofstream outputFile;
string testfile1;
string sum;
int total = 0;
int num;
cout << "Please input name of file." << endl;
cin >> testfile1;
cin.get();
inputFile.open(testfile1.c_str());
if (inputFile.fail()) {
inputFile.clear();
cout << "could not access testfile1" << endl;
return(1);
}
while (!inputFile.eof()) {
inputFile >> num;
total = total + num;
inputFile.close();
}
outputFile.open(sum.c_str());
outputFile << total << endl;
outputFile.close();
if (outputFile.fail()) {
cout << "could not access file." << endl;
return 1;
}
return 0;
}
Question:
How can I make this program find and open the testfile1.txt?
Note:
I am pretty sure that when prompted for the file name, I did not misspell.
Here are few remarks that will help you figure out the possible problem:
1.You could reduce some lines of code by attaching your streams to a file during definition, instead of defining them and then use open, like so:
ifstream inputFile(testfile1.c_str());
2.To check if a file is open (and handle if it couldn't):
if (!inputFile) error ("Can't open input file: ", testfile1);
and:
if (!outputFile) error ("Can't open output file: ", sum);
right after the definition.
3.All open files are implicitly closed at the end of the program (or a function that contains them), so there is no need to explicitly close() them.
4.To read the contents of the input file and sum them:
int sum = 0;
string line;
// read a line
while (getline(inputFile, line)) {
stringstream ss(line);
// assuming you are reading integers separated by white space
int num = 0;
// extract each number on the line
while (ss >> num) total += num;
// reset line
line.erase();
}
Note: test and modify your code according to your specific needs. A side note: you could probably omit: cin.get(); in your code.
use getline (std::cin,name);
for input name
and use proper function of ostream for reading and writing.
you'r getting input wrong at line 21 and line 22