I have the task to write a function that reads a line from a text file (renamed to .dat, however it contains only text), but I am out of options for a solution because of the following points:
I am using Borland C++ Version 5.02, and no, I CAN´T download another compiler because I dont have admin rights on my laptop and the guy who has the needed password isnt there until next week.
The compiler does not accept using namespace std, and also it doesnt accept getline(), no matter if string and iostream are included or not.
I am trying to find a solution or at least the tiniest approach, but I am unable to find one.
So my question is: How do I read a line from a simple textfile without using getline() (cin.getline works, the ones from string or fstream doesnt) ? The textfile contains several lines like these:
1234;12.05.03;08:44:23; XY12-AB;A1-12;Timeout
2345;12.05.03;09:04:34;XY1-CD;A22-9;Connection refused
And the numbers/letters between the ; need to be stored in variables so they can be worked with.
Im not asking for you to write my code, but I am reallyreaylly frustrated and my instructor is no help.
Live long and prosper,
Me.
http://www.cplusplus.com/reference/string/string/getline/
If you cant use (which you really shouldnt)
using namespace std
Then refer to your namespace with :: operator
For example:
std::string
Now try to write your own code using std:: and comment if you still cant do it.
Also, there is a lot of other options than std::getline() to read line of text.
Ref: Read file line by line
Option 1:
Try using the C's fgets() function.
Option 2:
You mention that cin.getline() works. You can freopen stdin with the input file and then cin will point to mentioned file. After that cin.getline() will read from the file:
Downside: After the freopen you will not be able to accept any input from the user.
Example: Note this has not been tried using g++ but I guess it should work with Borland too.
#include <iostream>
#include <stdio.h>
int main() {
char buf[1000];
freopen("somefile.dat", "r", stdin);
while (cin.getline(buf, sizeof(buf)).good()) {
// Now buf contains a line
// Do something with it
}
return 0;
}
Try using
getline(cin >> ws, variableName);
But first, you have to use
using namespace std;
I'm having the same problem while i using multi dimensional array on structs into a file, i have try different ways. But then i tried this one and it's work for me.
So in my case it gonna be like this
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myFile;
myFile.open("test.txt");
int count = 0;
while (!myFile.eof())
{
getline(myFile >> ws, data[count].string1);
getline(myFile >> ws, data[count].string2);
myFile >> data[count].int1;
for (int i = 0; i < data[count].int1; i++) {
getline(myFile >> ws, data[count].data2[i].string3);
}
count++;
}
return 0;
}
For more : https://www.geeksforgeeks.org/problem-with-getline-after-cin/
Related
Im using string library but I can't seem to use the get line function
used both string and string.h but its still not working
I've added the code below and it basically is just to use input numbers in a text file and then using them in a sorting mehthod
the problem is that im only getting the error mentioned below and can't seem to wrap my head around the solution to it
,,assignmentDTS.cpp:34:17: error: no matching function for call to 'getline'
getline(inputFile,tempnumstring);
#include<iostream>
#include<fstream>
#include<string.h>
#include<time.h>
using namespace std;
class sorting {
public:
void bubblesort(int arraySize){
int num;
int *arr=new int[arraySize];
ofstream inputFile("data.txt");
if(inputFile.is_open()){
for (int i = 0; i <arraySize; i++){
string tempnumstring;
std::getline(inputFile,tempnumstring);
num=stoi(tempnumstring);
arr[i]=num;
}
And there we go: ofstream inputFile("data.txt"); needs to be ifstream inputFile("data.txt"); The fstream starts with i for input stream, rather than o for output stream.
Answered on chat
std::getline is declared in #include <string> per the C++ Library Standard.
The #include <string.h> statement includes the C Library Standard string library which has no getline function. This header contains functions like memcpy and strcpy.
The C++ recommended way to reference the C "string.h" header is #include <cstring>.
I'm a beginner and I'm trying to transform from previous version of c++ to modern c++17.
I'm trying to read lines from a file. The contents are mostly gibberish and I'm doing this as an exercise to learn the language after not using c++ for many years.
The contents of the file I'm reading from are gibberish, i.e:
werweirwer
weriwrwjeie
werjiwrji
(after solving this I'll use it as an exercise to assign lines after filtering as input to constructors, use regex on it and basically develop it until I feel comfortable enough with input/out concepts, which may take some time).
However, it cannot read from the input file, even though it exists and in the same directory as the .cpp file (with reading permissions). IDE is clion if it matters.
Here's the code I used:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
std::vector<std::string> insertToVector(std::string k){
std::vector<std::string> wordvector;
if(k.empty()) {cerr<<"error reading from file: string is empty";}
else {wordvector.push_back(k);}
return wordvector;
}
int main() {
fstream f("k.txt",ios_base::in);
std::string templine;
if(f){
cout<<"Contents: \n";
while(getline(f, templine)){
cout<<"Contents:"<< templine; //just to output it simply
std::vector<std::string> wordvector= insertToVector(templine);
std::for_each(wordvector.begin(),wordvector.end(),[](const std::string word){std::cout<<word;}); //vector output
}
}else{
std::cerr<<"couldn't open file";
}
f.close();
return 0;
}
Additional question I wonder whether it is good to read lines with while(getline()) or to use while(!f.eof()) instead? Which is better in your opinion?
One more thing, I'm quite confused with functors and std::function, could you show me how to implement the insertToVector as std::function or functor and call it correctly?
Thank you very much. Doing my best to learn
EDIT: Fixed it using auto path = fs::path, and then using that reference with fstream. Worked well. Thank you very much for your explanations in the comments. Helped a lot in learning.
Check if a string is palindrome
I was using the link above to try to solve this problem (among many others, Ive been trying to solve it various ways all day with no dice, this is my first C++). All other examples are usually in an array format, and I can't make assumptions as to the length of a word.
I'm trying to make a program to detect if a word is a palindrome or not. I have a text file with one word per line, and want to test each word, line by line, if it is a palindrome, and if so to print it to the screen, and if not, to ignore it and not print it.
I figured the best way to locate the palindromes was to reverse the word line by line and match it to the original, and if they are the same (==), then to print it. Here is what I have so far:
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
std::string line;
std::ifstream infile("wordlist.txt");
}
string reverse(string line){
if (line == string(line.rbegin(), line.rend())) {
cout << string;
}
}
All help is appreciated
I guess your question is a homework question and you would like to get some information on how to complete the C++ coding.
You look not to know how to read file contents in C++.
Here's a link of how to do it:
Read file-contents into a string in C++
I am not very sure about what you specifically would like to be answered. If your question is a homework question, here's some info of how to ask:
https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions
#include<iostream>
#include<algorithm>
#include<string.h>
#include<fstream>
using namespace std;
int main() {
string line="", line_rev="";
ifstream infile;
infile.open("wordlist.txt");
do{
infile>>line;
line_rev=line;
reverse(line_rev.begin(), line_rev.end());
if(line==line_rev)
cout<<line<<endl;
}while(getline(infile, line));
//if(infile.is_open()){cout<<"open"<<endl;} //to check if file is open or not
//else{cout<<"unable to open"<<endl;}
return 0;
}
This is the solution. i dont know why you are writing "string reverse(string line)" out side the main() function.
I have searched through a lot of questions on this website which are pretty much the same, but nothing works for me. In the first place, let me tell you that I am using Code::Blocks and I am using Ubuntu. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("code.out");
string write;
getline(cin, write);
file << write << "\n";
file.close();
}
Tried \n, tried \r\n (\r doesn't seem to do anything for me really). Oh and by the way, if you could also make it work with word-by-word reading that would be great. Thank you very much!
EDIT: Hey guys, I solved it. Thanks for the answers tho! I needed to add a ios::app after code.out!
Should you be using ofstream. http://www.cplusplus.com/reference/fstream/ofstream/
Then check that it has opened.
Then check you have read some data - debugger is handy for that
EDIT
You need
ofstream file("code.out", ios::out | ios::app)
Try this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file("code.out", std::fstream::out);
string write;
getline(cin, write);
file << write << '\n';
file.close();
}
Explicitly passing the std::fstream::out through the constructor got it to behave correctly for me and produced the newline.
Edit:
Note for future reference, my solution produces the newline but this will overwrite data currently found in the file. Ed Heal has code for appending to a file in his answer.
Adding
std::fstream::app
to my code would then mimic Ed Helms solution. Please mark his answer if appending functionality is actually what you needed. This answer will be for others who have a similar newline issue who want to overwrite the file.
I also had that problem once.
Try using ofstream instead of fstream. Maby that'll help, because I used that too.
I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?¨
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}