I/O redirection in C++ - c++

I wrote a program that takes its input from a file (using ifstream), uses a bunch of std::getline to extract the data and manipulate it.
I want to use I/O redirection so that these lines can be used using std::cin (As if someone is typing this info). I looked it up but I didn't quite understand how I would implement it using the Visual Studio Community program. Any help is greatly appreciated.

I would suggest you to use a stringstream for that:
#include <iostream>
#include <sstream>
int main() {
string z = "100";
stringstream a("");
a << z;
int x;
a >> z; // Extracts data; a works like cin would have if it were used to input data
cout << z;
return 0;
}

I found the solution to my question!
I simply changed the following line of code from:
std::ifstream datastream(text file location);
while (std::getline(datastream, output_str)) {
.
stuff...
.
}
To:
while (std::cin(datastream, output_str));
Once I compiled my code with no errors and got my ./a.out, I typed in my compiler:
./a.out < text file
And that pretty much started inputting the file content into std::cin as if someone was typing it.

Related

Issues reading floats from .txt file

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.

Write a program that takes in a line of text as input, and outputs that line of text in reverse. C++

Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text.
Ex: If the input is:
Hello
there
Hey
quit
Then the output is:
ereht
olleH
yeH
I tried this, but for some reason, it is giving me a new line in when a print the code and I do not know how to fix it, please help.
#include <iostream>
#include <string>
using namespace std;
int main() {
string userInput;
while (true)
{
string check = userInput;
if (check =="quit" || check == "Quit" || check =="q") {
break;
}
string reverse = "";
for (int i = userInput.length() - 1; i >= 0; i--) {
reverse = reverse + userInput.at(i);
}
cout << reverse << endl;
cin >> userInput;
}
return 0;
}
Your input statement
cin >> userInput;
happens only at the end of your main. Try moving it at the start of your main.
Read this C++ reference website. Consider reading the C++11 standard n3337.
Read first some good C++ programming book, the documentation of your C++ compiler (e.g. GCC, invoked as g++ -Wall -Wextra -g), and the documentation of your debugger (e.g. GDB).
Take inspiration from existing open source C++ software
such as Qt, RefPerSys, GCC, the Clang static analyzer (which should be helpful), Fish, FLTK etc.... and many others on github or gitlab.
Read more about std::string and std::cin

Ifstream is opening the file, but doesn't output the lines inside the file

Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int x;
string line;
vector<int> vect;
ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt");
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt");
if (inFile.is_open()) {
while (getline(inFile, line))
{
cout << line << '\n';
}
inFile.close();
}
else {
cout << "Unable to open file";
exit(1); // terminate with error
}
return 0;
}
The path to the file that i wrote is correct such that the file opens, but when the program runs it doesn´t cout the lines that i wrote on the txt file to the cmd, i dont know if this is somewhat important but im coding in visual studio 2019.
I can't seem to find the answer to this problem anywhere in the internet and to be honest i think im doing it right, any help would be much appreciated,thanks in advance.
You are trying to open the inFile twice. First time during inFile construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt"), second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt"), when it's already open, which is erroneous, and flags the stream as no longer good.
3 possible fixes:
Remove inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
Use default constructor, without specifying the file name
inFile.close() before you open it again (obviously, not the nicest fix).

c++ text file redirection getline infinite loop

So I'm having an issue where I am reading in a text file using cin. Here is a basic idea of my code:
while(getline(cin,line) {
cout << line << endl;
}
//Do some task
return 0;
The problem I'm running into is that the loop will not terminate and //Do some task will never run. The only solution that I've found is to look directly at the text file, see how many lines of text there are, and hard code a conditional to break out of it. So say I have a text file with 5 lines and an variable int row. Then I would do something like this:
while(getline(cin,line) {
cout << line << endl;
if(row == 5) {
break;
}
//Do some task
return 0;
I tried googling but I can't seem to find an answer anywhere. Any ideas? And also only libraries I'm allowed to use is iostream.
You can use rdbuf to redirect your cin output
Following Link will help you.
http://www.cplusplus.com/reference/ios/ios/rdbuf/
The following code block should solve your issue:
Credit goes to the author: kevinchkin
http://www.cplusplus.com/forum/beginner/8388/
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout<<output;
}
}
myReadFile.close();
return 0;
}
This is a basic template for reading from a .txt file. I also can not think of any reason why you should not be able to use more than just iostream. They make the other libraries because iostream isn't the best way to go about it.
Most(if not all) Teachers/Professors I have had like it when students go above and beyond what the class is studying, and try to learn more.
If you need additional help, take a look at: http://www.cplusplus.com/doc/tutorial/files/

Reading strings and integers from .txt file and printing output as strings only

I'm new to C++, and I'm trying to write a short C++ program that reads lines of
text from a file, with each line containing one integer key and one alphanumeric string value (no embedded whitespace). The number of lines is not known in advance, (i.e., keep reading lines until end of file is reached). The program needs to use the 'std::map' data structure to store integers and strings read from input (and to associate integers with strings). The program then needs to output string values (but not integer values) to standard output, 1 per line, sorted by integer key values (smallest to largest). So, for example, suppose I have a text file called "data.txt" which contains the following three lines:
10 dog
-50 horse
0 cat
-12 zebra
14 walrus
The output should then be:
horse
zebra
cat
dog
walrus
I've pasted below the progress I've made so far on my C++ program:
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
using std::map;
int main ()
{
string name;
signed int value;
ifstream myfile ("data.txt");
while (! myfile.eof() )
{
getline(myfile,name,'\n');
myfile >> value >> name;
cout << name << endl;
}
return 0;
myfile.close();
}
Unfortunately, this produces the following incorrect output:
horse
cat
zebra
walrus
If anyone has any tips, hints, suggestions, etc. on changes and revisions
I need to make to the program to get it to work as needed, can you please
let me know?
Thanks!
See it:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name;
int value;
ifstream myfile("text.txt", ifstream::in);
while(myfile >> value >> name)
cout << name << endl;
return 0;
}
You are having problems because you attempt to read each line twice: first with getline and then with operator>>.
You haven't actually used std::map in any regard, at all. You need to insert the integer/string pair into the map, and then iterate over it as the output. And there's no need to close() the stream.
Instead of using "! myfile.eof()" use this code it will help.
ifstream is;
string srg;
is.open(filename);
while(getline(is,srg))
{//your code
}