Having an input that already have a text in it in c++ - c++

Just a question, is there anyway that I can have an input with a text already written for me with using "cin." I'm looking for a predefined function or whatever that I can use to have inputs with a text in it. My purpose of that is that I'm trying to make a simple text editor in command-line. Even if there aren't any predefined functions, anyone have a pseudocode to copy a string of words into a cin (or any other input). I hope that my question is not vague pointless.
Regards.

You can assign the buffer of std::cin to read from a file on disk instead of the terminal, like this:
ifstream file("file.txt");
cin.rdbuf(file.rdbuf());
From then on, when you read from cin it will give you the contents of file.txt.
If you prefer you can also make std::cin produce text directly from a string, like this:
istringstream stream("blah\nblah blah");
cin.rdbuf(stream.rdbuf());
Now when you read from cin you will get two lines: blah and blah blah.

Related

Ignoring remaining newlines and white space when reading input file (C++)

I have a function that reads a text file as input and stores the data in a vector.
It works, as long as the text file doesn't contain any extra new lines or white space.
Here is the code I currently have:
std::ifstream dataStream;
dataStream.open(inputFileName, std::ios_base::in);
std::string pushThis;
while(dataStream >> pushThis){
dataVector.push_back(pushThis);
}
For example:
safe mace
bait mate
The above works as an input text file.
This does not work:
safe mace
bait mate
Is there any way to stop the stream once you reach the final character in the file, while still maintaining separation via white space between words in order to add them to something like a vector, stack, whatever?
i.e. a vector would contain ['safe', 'mace', 'bait', 'mate']
Answer:
The problem came from having two streams, one using !dataStream.eof() and the other using dataStream >> pushThis.
Fixed so that both use dataStream >> pushThis.
For future reference for myself and others who may find this:
Don't use eof() unless you want to grab the ending bit(s) of a file (whitespace inclusive).

C++ Reading from a file given by user [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm creating a simple directory program that allow user to enter a file name and search that file by name, address, or phone number. I'm having trouble properly reading the file.
If someone could give me suggestions on how to fix my getFirstName function. The function should read the first word of the file.
Example file:
Bob Smith 123456789
123 Main Street
Susan Smith 1224445555
543 Market Street
Here is part of my code so far.
string file;
string first;
int main() {
ifstream inFile;
cout<<"Enter file name: ";
cin>> file;
inFile.open(file);
if(inData.fail()) {
cout<<"INVAILD";
}
getFirstName(first);
}
void getFirstName(string f, inFile file) {
file.open(f);
while(file.good(f)) {
file>>f;
}
if (file.bad()) {
cout<<"Name not found";
}
}
i will not write you the program, but let me point you in a direction.
first of all: please format your code better. maybe its just because stackoverflow, but there should be consistent and sensefull formatting of your code, otherwise you and others cant read it well and have trouble finding problems. (plz google clang-format for a tool, maybe an ide would do it as well).
split your programm in different logical parts. my approach would be:
open file, if not possible give warning, end program
read file content into a string IN: filename, OUT: string of content
split the string into line, IN: string, OUT: std::vector
for each line, split the line into parts(3 elements?) IN: linestring, OUT: name, street, ...
You can that in proper datastructures, plz see the STL for good ones
Access your datastructure for the wanted information.
Proposal for your data.
istream for file, you have that
std::string for file content
std::vector for line wise filecontent
std::unordered_map map the name to information.
this should give you a googling start. each subproblem can be solved independent (and tested) and is easier to find on SO :)
Good luck.
I agree with the comments. Yet to answer your issue "The function should read the first word of the file." below is a general idea how you can read the first word from file:
...
ifstream inFile; // define your input stream
string firstwrd; // first word
inFile.open("yourfile"); // open your file
inFile>> firstwrd; // this will read the first word
inFile.close(); // close the file
...
And please consider reading through Jonas`s comments.
Edit: Please note my answer by no means is the definitive tutorial of best practices of reading from file. It applies your specific case.
HTH!
Before you can even begin to start programming, you have to identify the exact format of the file you want to read. That format gives you the order of operations for how you intend to read from the file.
In your example, you give:
Bob Smith 123456789
123 Main Street
Susan Smith 1224445555
543 Market Street
Which is broken down into a by-line format of:
[First Name] [Last Name] [User ID (I assume)]\n
[Address]
So now that we have that established, the first thing we do is open the file stream.
ifstream file("path\\to\\file");
When it comes to retrieving information from a file stream, there are 2 standard methods: the >> operator and getline().
The >> operator returns the very next block of text in a given fstream up to any whitespace character such as space, newline or return characters. The syntax for this is file >> var where file is the fstream you intend you read from and var is the variable you want to write to.
The getline() function will return the entire line, including spaces, but will stop at return and newline characters. The actual syntax of the function is std::getline(read, write); where read is the file stream or string you intend to actually read from and write is the variable you intend to copy the real line to.
For example:
ifstream file("file.txt");
string firstname, lastname, id, address;
file >> firstname; //get the first word of the file.
file >> lastname; //get the second word of the file.
file >> id; //get the third word of the file.
getline(file, address); //Get the next whole line of the file, regardless of how many words.
A funny quirk is that you don't have to worry about manually telling C++ where in the file you're wanting to look for the data. As the file is read a pointer is automatically kept inside of the file stream of where to begin reading from next. When you get one word, the pointer automatically starts at the beginning of the next word, so you just keep pulling data linearly until you reach the end of the file.
void getFirstName(string f, inFile file); should be void getFirstName(string f, ifstream inFile);.
And remember, put an ampersand (&) between the type of the variable and the name to avoid creating a copy of the file (that consumes more ram), not putting the ampersand is only reasonable to use if you want to make changes to the variable that should not stick around.
And where is string f defined? You call the function without passing f but it's used in the function. That is a serious problem.
The ifstream.good() function if I remember correctly can't take parameters.
If you're trying to find f (you didn't tell us what it is so I can't be more precise) then you should first understand that f should be a file (since you used file.open(f);), pass the value to a string, and after doing inFile >> name_of_your_string; do if (name_of_your_string == f) { /* the last word read corresponds to f */}.
The type is ifstream, and the variable's name is inFile.
Also since getFirstName is defined after main, you got to put this before main void getFirstName(string f, ifstream inFile); this is called a prototype, and it tells the compiler that the function is after main.
Obviously don't remove the rest of the function. If that's a problem for you move main under it. Also if someone puts a space in the input everything before the last space will be lost, remove cin >> file; and use getline (cin, file);
Remember to update the answer with more details on what f is and what exactly you want it to do.
EDIT: Remember to use inFile.close(); after you stop reading the file to avoid subtle errors.

Is it possible to skip a line in a data file?

I have a data file that I am trying to input and the data is split into sections via a blank line. The data will be read in from a text file.
How do I make my code skip a blank line to read in the next piece of data? I am currently just in the planning stages of my application.
I'm a beginner so I'm not really sure how to go about this.
Can anyone advise a method on how to approach this?
I have just written it out and my code looks like this:
string ship2_id;
char ship2_journey_id[20];
float ship2_l;
int ship2_s;
getline(itinerary_file, ship2_id);
if (ship2_id = ' ')
{
itinerary_file.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
getline(itinerary_file, ship2_id);
cout << ship2_id << endl;
Yes,
stream.ignore(max_number_of_chars_to_be_skipped, '\n');
I usually just use 1ul<<30 or similar for the first parameter, but
this could be a DoS vector if the input is untrusted and slow to skip those chars
the "pedant" value would read std::numeric_limits<std::stream_pos>::max() or similar
I don't what are you using to read the file, but, to search for a blank line, look for two "line breaks" together. Take in account that the "line breaker" character is different for some OS. In Windows, by default, there are two characters that are used together for a line break.

Loading a Linux formatted text file using a C++ windows application

My problem is I am trying to load a Linux formatted text file and read it regularly as is one was opening up a windows formatted text file in a C++ application. I have gotten it to work perfectly when the file is formatted exactly how I want it to be in windows and have the data form the file loaded into a list of lists.
To try to describe my problem a little better what I am currently able to do right now is if I have a file which is tab delimited I am able to store all of the contents from each row into a list of strings where each string is whatever each tab is separating. I then have a list of all of the rows.
For example my text file I'm reading my look something like this:
156 Hit 83.2 23:34
23 Miss 21.4 23:38
and so on....
This code spinet below is what I have been using, which I had found help elsewhere and altered it to work how I needed it to. It will create a list with two items in the list where each of the items contains a list of 4 strings each string representing the contents in each of "columns" for the current row. Hope this is explained thorough enough.
ifstream infile(file);
list <list <string> > data;
while (infile){
string s;
if (!getline( infile, s )) break;
std::istringstream ss ( s );
list <string> record;
while (ss){
string s;
if (!getline( ss, s, '\t' )) break;
record.push_back( s );
}
data.push_back( record );
}
That is exactly what I would like to do however instead of the text file I would be reading from being formatted as a Windows text file it will be a Linux text file and will not have a tab in-between each "item" in each row; but instead will contain a random number of spaces. My thought was I could open the file up in binary mode and read it that way and instead of having a tab be my delimiter I could choose any amount of white space. However I am not exactly sure how to do that as I am still relatively new to C++ and have not specifically worked with reading Linux formatted text files from a Windows C++ application. Any help would be greatly appreciated. Thanks in advance!
This has nothing to do with Linux versus Windows. You can use >> to perform formatted input of whitespace-separated fields:
string s;
while (ss >> s)
record.push_back(s);
To skip whitespace explicitly, use std::ws; to disable whitespace skipping, use std::noskipws.

How do you read a word in from a file in C++?

So I was feeling bored and decided I wanted to make a hangman game. I did an assignment like this back in high school when I first took C++. But this was before I even too geometry, so unfortunately I didn't do well in any way shape or form in it, and after the semester I trashed everything in a fit of rage.
I'm looking to make a txt document and just throw in a whole bunch of words
(ie:
test
love
hungery
flummuxed
discombobulated
pie
awkward
you
get
the
idea
)
So here's my question:
How do I get C++ to read a random word from the document?
I have a feeling #include<ctime> will be needed, as well as srand(time(0)); to get some kind of pseudorandom choice...but I haven't the foggiest on how to have a random word taken from a file...any suggestions?
Thanks ahead of time!
Here's a rough sketch, assuming that the words are separated by whitespaces (space, tab, newline, etc):
vector<string> words;
ifstream in("words.txt");
while(in) {
string word;
in >> word;
words.push_back(word);
}
string r=words[rand()%words.size()];
The operator >> used on a string will read 1 (white) space separated word from a stream.
So the question is do you want to read the file each time you pick a word or do you want to load the file into memory and then pick up the word from a memory structure. Without more information I can only guess.
Pick a Word from a file:
// Note a an ifstream is also an istream.
std::string pickWordFromAStream(std::istream& s,std::size_t pos)
{
std::istream_iterator<std::string> iter(s);
for(;pos;--pos)
{ ++iter;
}
// This code assumes that pos is smaller or equal to
// the number of words in the file
return *iter;
}
Load a file into memory:
void loadStreamIntoVector(std::istream& s,std::vector<std::string> words)
{
std::copy(std::istream_iterator<std::string>(s),
std::istream_iterator<std::string>(),
std::back_inserter(words)
);
}
Generating a random number should be easy enough. Assuming you only want psudo-random.
I would recommend creating a plain text file (.txt) in Notepad and using the standard C file APIs (fopen(), and fread()) to read from it. You can use fgets() to read each line one at a time.
Once you have your plain text file, just read each line into an array and then randomly choose an entry in the array using the method you've suggested above.