How would I split a string by number of characters using getline? - c++

Is there a way to take in a specified number of characters using cin or getline from a txt file and stop reading once the character limit is reached? I would like to read exactly 15 characters from a text file without stopping at any blank spaces or other delimiting characters.
ifstream inFile;
inFile.open("file.txt");
string sname;
//this is what I put at the moment but I don't believe it serves the purpose of what I'm looking for
cin >> setw(15) >> sname;
I went through previously posted questions but I couldn't find a clear answer.

I don't think you can do that with getline() or cin,
but this should works:
#include <fstream>
#include <string>
int main()
{
std::ifstream inFile;
inFile.open("file.txt");
std::string sname;
sname.resize(15);
inFile.read(&sname[0], 15 * sizeof(char));
}

Related

C++ Reading Text File and Storing Data

data.txt contains the following information: firstName, lastName, salary, increment.
James Chong 5000 3
Peter Sun 1000 5
Leon Tan 9500 2
I want to read data.txt, make the necessary calculations, and store the output of 3 variables in anewData.txt:
firstName, lastName, updatedSalary(salary*percentageIncrement)
I only managed to proceed to reading and display information in data.
Below is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string filename = "data.txt";
ifstream infile;
infile.open(filename);
//if file cannot open, exit program
if (!infile.is_open()){
exit(EXIT_FAILURE);
}
string word;
infile >> word;
while(infile.good()){
cout << word << " ";
infile >> word;
}
system("pause");
return 0;
}
May I know are there any references that I can make use of? Thank you
I am not entirely sure about the question , but you might find substr function useful (if you need to process the data),about writing to a file, you can just create an ofstream output("newData.txt") and simply write the result there. (output << result). Also there is a tokenizer library in BOOST if you don't want to solve it with substr.
You're expecting each line to have 4 words separated by whitespace, so it's as easy as extracting them from infile at each iteration:
while(infile.good()) {
string first_name, last_name;
infile >> first_name;
infile >> last_name;
unsigned int salary, increment;
infile >> salary;
infile >> increment;
}
of course you should check that infile is good after attempting to extract the various pieces, should the lines be malformed.
You can get fancier here, but this covers your basic needs.

Removing letter code gone wrong (C++)

I was writing this code below that is suppose to take in information from the user ( a sentence ) and remove the desired letter. However, it only works if that sentence is one word. If the information contains a space, it will terminate at the space.Any advice as how I can get the program to read the entire sentence?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string sentence;
char letterRemoved;
//Entering in Information
cout <<"Enter a sentence here!";
cin >> sentence;
cout <<"Enter letter to remove";
cin>>letterRemoved;
//Removing Occurence of letter
sentence.erase(remove(sentence.begin(), sentence.end(),letterRemoved), sentence.end());
//Print out
cout<<sentence << "\n";
return 0;
}
Reading input using cin >> sentence only reads until whitespace is encountered, and then stops. If you want to read an entire line (until the user presses enter), you want to use std::getline:
getline(cin, sentence);
Alternately, if you want to read up until a full stop character or a newline is found, you can use the delimeter argument to getline:
getline(cin, sentence, '.');

Full String is not showing in C++ program

I have following Simple program to print string in C++, But this program only reads characters before space, not reading full string.
#include<iostream>
using namespace std;
int main()
{
char str[90];
cout << "Enter a string:";
cin >> str;
cout << str;
system("pause");
}
This is by design: cin "breaks" lines on whitespace characters, such as spaces and tabs.
Moreover, you are limiting the input to 90 characters, which is not good either: typing more than 90 characters with no spaces in between would overflow the buffer.
Here is a way to fix it:
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
Unlike character arrays, std::string objects can grow dynamically, so they would accommodate any number of characters the user chooses to enter.
You need to add two headers in order for this to compile:
#include <string>
#include <iostream>
>> reads a single word. You want getline to read a whole line:
cin.getline(str, sizeof str);
Now the problem is that the line will be truncated if it's too long. To fix that, use a string rather than a fixed-size buffer:
string str;
getline(cin, str);

Getting input from file troubles C++

I've been trying to read some information in from a .txt file in C++ but it's not all working like I expect. Here is some example code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[255];
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
And test.txt contains:
1234
WordOne WordTwo
What I expect is for the code to print the two lines contained in the text file, but instead I just get:
1234
I've been reading about getline and istream but can't seem to find any solutions so any help would be appreciated.
Thanks
The newline character remains in the input stream after the read of the integer:
// Always check result to ensure variables correctly assigned a value.
if (input_stream >> value)
{
}
Then, the call to getline() reads the newline character and stops, producing an empty string. To correct, consume the newline character before calling getline() (options include using getline() or ignore()).
Note there is a version std::getline() that accepts a std::string as its argument to avoid using a fixed sized array of char, which is used incorrectly in the posted code.
ifstream's getline method gathers input until one of two options is hit. Either a terminating character or the size passed in is reached. In your case, the newline terminator is encountered before the size is reached.
Use another getline to retrieve the second line of text.
Reference
The problem you are seeing is that the first newline after 1234 is not consumed by input_stream>>(int); so the next getline only reads to the end of that file.
This is a very constructed scenario, commonly found in schoolwork. The more common scenario when reading a textfile is to consider the entire file as linebased text.
In this case the more convenient
string line;
while( std::getline( input_stream, line ) ){
}
is appropriate, and way less error prone.
The textfile would commonly have a predefined format. Perhaps name = value lines, and are parsed as such after the line is read from the file.
Here is a somewhat corrected version of your original code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[256]; // was 255
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.ignore(); // skip '\n'
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
Also, I would advise you to use a string instead of a char[] and use the other getline function.

C++ file input problem

Hi Guys! I have the following code:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MAXN 301
string names[MAXN];
vector<string> names_vec;
int main(int argc, char **argv)
{
ifstream fin(argv[1]);
int n;
fin>>n;
string line;
while(getline(fin, line))
names_vec.push_back(line);
for(int i=0; i<names_vec.size(); i++)
cout<<names_vec[i]<<endl;
return 0;
}
and names.in file for input:
5
CLEOpatra
AISHWARYA rai
jOHn f. KeNNeDy
leonardo DA Vinci
tyleR durdeN
When i compile it and run it first prints empty line, that names_vec[0] is empty line. Can anyone explain why and how can I fix it?
The problem is that you're mixing the >> operator with calls to getline. Generally, you want to use one or the other, but not both of them together.
The reason you get an empty string in your vector is because >> will NOT consume the whitespace which causes it to stop. That is, it reads the "5", finds the newline character after it, and then stops, leaving the newline character in the ifstream.
Then, the call to getline encounters the newline character and immediately says, "Done! I read a line!". It consumes the newline character and returns the entire string leading up to it -- which in this case was the empty string.
If you know that your data will be formatted properly (no invalid input), it might be easiest just to use >> to read the entire file. Otherwise, I would recommend using getline to read each line one at a time, then using a stringstream object to parse the data out of the line.
EDIT
I just noticed that the rest of your input has first/last names separated by spaces. Since >> stops on spaces, it would probably be easiest to use getline to read the entire file. Example of reading the 5:
string line;
getline(fin, line);
stringstream converter;
converter << line;
int n;
converter >> n;