Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Say I have a textfile "Employees.txt" with Employee name and ID.
Like so:
John:d4250
Sarah:s5355
Alan:r4350
If I have a very very basic Employee class which has a constructor for Name and ID
and I wish to read from this textfile and insert them into a vector
Am I best to use something like:
void GenericProgram::loadEmployees()
{
string line;
ifstream empFile("employees.txt");
if(empFile.fail())
{
cout << "input file opening failed\n" << endl;
exit(EXIT_FAILURE);
}
while (!empFile.eof())
{
string empName;
string empID;
while (getline(empFile, line, '\n'))
{
// this will give me the line on its own
// now how to delimit again using ':'
// then do something like
Employee e(empName, empID)
employeeVector.push_back(e);
}
empFile.close();
}
}
I apologise that this is so basic. Brain is failing on me. I was wondering if there are better ways to read from files to populate objects with streams.
Just add to your code
int pos = line.find(":", 0);
if (pos != std::string::npos)
{
std::string empName(line.begin(), line.begin() + pos);
std::string empID(line.begin() + pos + 2, line.end());
}
For multiple ":"
std::vector<std::string> str;
std::vector<size_t> positions;
positions.push_back(0);
do
{
positions.push_back(line.find(":", positions.size() - 1));
}
while(positions[positions.size() - 1] != std::string::npos);
for (int i = 0; i < positions.size(); i+=2)
{
str.push_back((line.begin() + positions[i], line.begin() + positions[i+1]));
}
But i haven`t tested it.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
I want to read all files in specific directory.
for example
In directory a there are file1.text file2.txt a.txt c.txt
I want to know how many words are included in each file.
I made a code for a file.
But I don't know how to automatically move on next file at same directory.
int EBook::get_total_words()
{
ifstream ifs("inputs//a.txt");
int words = 0;
string word;
if (!ifs)
{
std::cout << "Unable to open file " << '\n';
exit(1);
}
while (ifs >> word) {
++words;
}
return words;
}
With std::filesystem you can do this:
std::string path_to_dir = '/some/path/';
for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){
std::cout << entry.path( ) << std::endl;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have been asked to develop program to count no. of lines and words in the file, this is my trial, my teacher said that I cant use >> operator for counting words and comparing but I could not handle it.
#include <iostream>
#include <fstream>
using namespace std;
int numberLines = 0;
int numberWords = 0;
void numberOfLines(){
cout<<"number of lines is " << numberLines << endl;
}
void numberWords(){
cout << "number of words is " << numberWords <<endl;
}
int main(){
string line;
char a = '';
ifstream myfile("files.txt");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
cout<< line << endl;
numberLines++;
}
if ( a == ' '){
NumberWords++;
}
}
myfile.close();
}
numberOfLines();
numberOfWords ();
}
What you can do is add a 3rd argument to getline(). This lets it pull data from the stream until it hits a character. Doing getline(cin, line, ' ')takes all the data until the next and puts it into line. Your code might look like:
while(getline(inFile, line))
{
++numlines;
stringstream lineStream(line);
while(getline(lineStream, line, ' '))
{
++numWords;
}
}
The outer loop goes through the file and stores each line into line, then the inner goes through that line and counts each space. which correlates to a word.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i want to convert a sentence like 'good boy' to ascii code . i know the code that is a loop and print the ascii code of each character of sentence but i don't want this. i want that the ascii code of sentence (all characters alltogether) in long for example 1259788712..
You can use string to handle it.
#include <iostream>
#include <sstream> // use stringstream
using namespace std;
// turn int into string
string IntTOstring(int);
int main(void)
{
string sIn,sOut;
// input
sIn = "good boy";
sOut="";
for (int i=0 ; i<sIn.length() ; i++ ) {
// get one char from sIn each time
int temp=sIn.c_str()[i];
// turn int into string & save in sOut
sOut += IntTOstring(temp);
}
cout << sOut << endl;
return 0;
}
// use stringstream to convert int to string
string IntTOstring(int i){
stringstream ss;
ss << i;
return ss.str();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My problem sounds like this: I have as a input a huge string with numbers separated by whitespaces. I need to split this string and put the components in a vector and then to use its components. (then to transform to integers bla bla...).
I searched here for this but I did not understand some things entirely, so please a bit of explanation.
Also another question: why the following return one more "Substring: " in the end?
int main()
{
string s("10 20 30 50 2000");
istringstream iss(s);
while (iss)
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
}
system("pause");
return 0;
}
why the following return one more "Substring: " in the end?
Because your loop is broken; you're checking the stream state before reading from it. It's the same problem as described under:
Why is iostream::eof inside a loop condition considered wrong?
First count the amount of whitespaces like this:
int i = counter;
for( size_t i = 0; i < s.size(); ++i )
{
if( ' ' == s[i] )
{
++counter;
}
}
After that you have to substring in another for loop the string s.
Try the following approach
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
int main()
{
std::string s( "10 20 30 50 2000" );
std::istringstream is( s );
std::vector<std::string> v( ( std::istream_iterator<std::string>( is ) ),
std::istream_iterator<std::string>() );
for ( const std::string &t : v ) std::cout << t << std::endl;
return 0;
}
The output is
10
20
30
50
2000
You could initially define the vector as having type std::vector<int> and in the vector initialization use iterator std::istream_iterator<int>.
As for your second question then before outputing a string you have to check whether it was read. So the correct loop will look like
string sub;
while ( iss >> sub )
{
cout << "Substring: " << sub << endl;
}
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 8 years ago.
Improve this question
I want to separate string by character "," or ";".
std::string input = "abc,def;ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) { //how to add here ";"?
std::cout << token << '\n';
}
Use the Boost Tokenizer library:
boost::char_separator<char> sep(",;");
boost::tokenizer<boost::char_separator<char>> tokens(input, sep);
what about old way style?
std::string string = "abc,def;ghi";
std::vector<std::string>strings;
std::string temp;
for(int i=0; i < string.length(); i++)
{
if(string[i] == ',' || string[i] == ';')
{
strings.push_back(temp);
temp.clear();
}
else
{
temp += string[i];
}
}
strings.push_back(temp);
live demo
Using strsep in string.h from C library , you could do it like this:
std::string input = "abc,def;ghi";
const char* ss = intput.c_str();
const char token[] = ",;";
for (const char* part; (part = strsep(&ss, token)) != NULL;) {
std::cout<< part << std::endl;
}