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 6 years ago.
Improve this question
As the title suggests I am trying to find a specific word inside a file, and then deleting the line including it, but what I do here destroys the content of the file:
cin>>ID; //id of the line we want to delete
ifstream read;
read.open("infos.txt");
ofstream write;
write.open("infos.txt");
while (read >> name >> surname >> id) {
if (ID != id) {
write << name << " " << surname << " " << id << endl;
}
else write << " ";
}
read.close();
write.close();
Both of your files have same name. Calling basic_ofstream::open destroys content of a file if it already exists. In your case you destroyed data in input file before doing anything. Use different name and later rename. I assume line in input is ended with "\n" so we can use getline(). Then we need to tell if word is present in line and for that there is this function. std::string:npos is returned if line doesn't contain word.
#include <cstdio> // include for std::rename
#include <fstream>
#include <string>
void removeID() {
std::string ID;
cin >> ID; //id of the line we want to delete
ifstream read("infos.txt");
ofstream write("tmp.txt");
if (read.is_open()) {
std::string line;
while (getline(read, line)) {
if (line.find(ID) != std::string::npos)
write << line;
}
} else {
std::cerr << "Error: coudn't open file\n";
/* additional handle */
}
read.close();
write.close();
std::remove("infos.txt");
std::rename("tmp.txt", "infos.txt");
}
Related
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 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 6 years ago.
Improve this question
My task is to search for a string in .c file and modify it using c++ code. Iam done till searching for the string but modifying it is giving an error. It gives the same error if i copy the contents of c file to a text file and try to modify it. So iam sure something is wrong with my code. Please help as iam a beginner. Thanks in advance.
My code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string s1, s2;
ifstream test("test.csv");
while (test.eof()==0) //test.eof() returns 0 if the file end is not reached
{
getline(test, s1, ','); //reads an entire line(row) till ',' to s1
getline(test, s2, '\n');
cout << s1 + "= " +s2 << endl;
fstream fileInput;
int offset;
string line;
string search=s1;
fileInput.open("IO_CAN_0_User.c");
if(fileInput.is_open()) {
while(!fileInput.eof()) {
getline(fileInput, line);
if ((offset = line.find(search, 0)) != string::npos) {
cout << "found: " << search << endl;
string str;
str=search;
str.replace(str.begin()+25,str.begin()+31,"=s2 //");
break;
}
}
//cout << "string not found" << endl;
fileInput.close();
}
else cout << "Unable to open file.";
if(test.eof()!=0)
cout<<"end of file reached"<<endl;
getchar();
return 0;
}
}
The error your are facing is not clear, but I can see one big issue, your running replace on an empty string.
Your code:
string str;
search=str;
str.replace(str.begin()+25,str.begin()+31,"=s2 //");
You create str (by default initialized as empty string), assign it to search (therefore this string gets empty) and then you call replace trying to change from char 25 to 31, which are not there since the str is empty.
Update
Probably you need to fix the replace, but then you cannot expect the file to change: the string you are modifying is in memory, not a piece of your file.
Therefore I would change the code (using yours as much as possible):
* Adding output file
* Fixing the replace
* Saving every line of the input file (replacing if need) on the output
fileInput.open("IO_CAN_0_User.c");
ofstream fileOutput;
fileOutput.open("output.c");
if(fileInput.is_open() && fileOutput.is_open() ) {
while(!fileInput.eof()) {
getline(fileInput, line);
if ((offset = line.find(search, 0)) != string::npos) {
cout << "found: " << search << endl;
line.replace( offset, offset+search.size(), s2 );
}
fileOutput << line << '\n';
}
This question already has an answer here:
Cannot open input file
(1 answer)
Closed 7 years ago.
I am trying to create a program that asks the user for the name of a file, then opens the file, adds the sum of all the integers listed on the file, then writes that sum on an output file.
After writing my code and saving the testfile1.txt into the same folder as the program, the program keeps giving me the: "could not access testfile1" (message I output to notify myself that it is unable to open the testfile1.txt).
Here is what I have so far (skipped the lines with description blocks):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream inputFile;
ofstream outputFile;
string testfile1;
string sum;
int total = 0;
int num;
cout << "Please input name of file." << endl;
cin >> testfile1;
cin.get();
inputFile.open(testfile1.c_str());
if (inputFile.fail()) {
inputFile.clear();
cout << "could not access testfile1" << endl;
return(1);
}
while (!inputFile.eof()) {
inputFile >> num;
total = total + num;
inputFile.close();
}
outputFile.open(sum.c_str());
outputFile << total << endl;
outputFile.close();
if (outputFile.fail()) {
cout << "could not access file." << endl;
return 1;
}
return 0;
}
Question:
How can I make this program find and open the testfile1.txt?
Note:
I am pretty sure that when prompted for the file name, I did not misspell.
Here are few remarks that will help you figure out the possible problem:
1.You could reduce some lines of code by attaching your streams to a file during definition, instead of defining them and then use open, like so:
ifstream inputFile(testfile1.c_str());
2.To check if a file is open (and handle if it couldn't):
if (!inputFile) error ("Can't open input file: ", testfile1);
and:
if (!outputFile) error ("Can't open output file: ", sum);
right after the definition.
3.All open files are implicitly closed at the end of the program (or a function that contains them), so there is no need to explicitly close() them.
4.To read the contents of the input file and sum them:
int sum = 0;
string line;
// read a line
while (getline(inputFile, line)) {
stringstream ss(line);
// assuming you are reading integers separated by white space
int num = 0;
// extract each number on the line
while (ss >> num) total += num;
// reset line
line.erase();
}
Note: test and modify your code according to your specific needs. A side note: you could probably omit: cin.get(); in your code.
use getline (std::cin,name);
for input name
and use proper function of ostream for reading and writing.
you'r getting input wrong at line 21 and line 22
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 6 years ago.
Improve this question
I will first off say that yes, this is a homework assignment, but my teacher is really not too clear on how to do things.
I'm asked to, in c++, Write a function that will pass words from a file one at a time. The function will calculate the word length and then print out TO SCREEN the word and its length on its own line.
The main will open your input file, read it word by word in a loop and then pass the word into your function for it to be printed.
I know how to open a file using fstream and all that, read it word by word, but not in a loop or a function by the void readfile () one. My problem here is putting everything together.
This is my program to open a file, get the length and display it in a parallel array
//declare parallel arrays
string words [MAXSIZE];
//open files
outputFile.open("output.txt");
inputFile.open ("/Users/cathiedeane/Documents/CIS 22A/Lab 4/Lab 4 Part 2/lab4.txt");
//inputvalidation
while (!inputFile.eof())
{
for(int i = 0; i < MAXSIZE; ++i)
{
outputFile << words[i] << " " << endl;
inputFile >> words[i];
}
inputFile.close();
}
for (int i= 0; i <= MAXSIZE; i++)
{ cout << words[i] << ":" << words[i].size()<< endl;
outputFile << endl;
}
//close outputfile
outputFile.close();
return 0;
}
So basically your assignment is :
function read_word
/* what you have to work on */
end
function read_file_word_by_word
open file
while not end_of_file
word = read_word
print word, word_length
end
close file
end
To read a word, you need to define what it is. Usually it's a bunch of letters, delimited by other characters that are not letters (whitespace, commas, etc.).
You could read the file character by character and store them when they are letters until you encounter some other kind of character. What you have stored is a word, and you can get its length quite easily.
Tip: http://www.cplusplus.com/reference/istream/istream/get/ allows you to read a single character from a file.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void func(const string& word)
{
//set field width
cout.width(30);
cout << left << word << " " << word.size() << endl;
}
int main(int argc, char* argv[])
{
ifstream ifs("F:\\tmp\\test.txt");
if(ifs.fail())
{
cout << "fail to open file" << endl;
return -1;
}
_Ctypevec ct = _Getctype();
for(char ch = 0; ch < SCHAR_MAX; ch++)
{
//set all punctuations as field separator of extraction
if(ispunct(ch))
{
(const_cast<short*>(ct._Table))[ch] = ctype<char>::space;
}
}
//change the default locale object of ifstream
ifs.imbue(locale(ifs.getloc(), new ctype<char>(ct._Table)));
string word;
while(ifs >> word)
{
func(word);
}
ifs.close();
}
You'll obviously want to separate each word in to its own string index to store them in your array. To separate each word, establish a break point like char break = ' '; Then, while your IOStream is reading the file, just add the words to the index using an iterator (i++)
Now that some time has passed since you asked the question, I would like to add that this could be answered in a quite small amount of code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void printString( const string & str ) { // ignore the & for now, you'll get to it later.
cout << str << " : " << str.size() << endl;
}
int main() {
ifstream fin("your-file-name.txt");
if (!fin) {
cout << "Could not open file" << endl;
return 1;
}
string word; // You only need one word at a time.
while( fin >> word ) {
printString(word);
}
fin.close();
}
A small note on fin >> word, this expression returns true for as long as there was a word read into the string. It will also skip any whitespace (tab, space and newline) by default.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a menu that that starts some methods based on user's choice. Two of the methods however don't work properly, and I have no idea why.
This is the part of the menu for them:
case 2:
{
string fileName;
cout << "Which file to read?:";
cin>>fileName;
this->ReadFromFile(fileName);
break;
}
case 3:
{
string fileName;
cout << "Enter name for the file:";
cin>>fileName;
this->WriteToFile(fileName);
break;
}
Here are the methods:
void ReadFromFile(string file)
{
string line;
ifstream rfile ("FileSystem/" + file);//open file for reading
if (rfile.is_open())
{
while(getline(rfile, line))
{
cout << line << endl;
}
}
else
{
cout << "An error occurred when tried to read from this file." << endl;
}
rfile.close();
_getch();
}
void WriteToFile(string fileName)
{
ofstream myFile;
ifstream exists (fileName);//open read stream to check if file exists
if(exists)//returns true if file can be opened and false if it cant
{
exists.close();//close the stream
myFile.open(fileName, ios_base::app);// open file for reading(ostream)
}
else
{
exists.close();
CreateFile(fileName);//file doenst exists, so we create one and list it in the file tree
myFile.open("FileSystem/" + fileName, ios_base::app);// open file for reading(ostream)
}
if(myFile.is_open())
{
string input;
cout << "start writing and press enter to finish. It will be done better later." << endl;
cin>>input;
myFile << input;
}
else
{
cout<<"An error occurred when tried to open this file."<<endl;
}
myFile.close();
_getch();
}
Now here is the funny part. When I try to write something to a file, it doesn't matter that I open it with: 'ios_base::app' or 'ios:app' it just rewrites it. But it cant even do that properly. If i have a line with whitespaces like'Hi this is me.' for example, it only writes the first word, which here is 'Hi'.
So if I then decide to read the file the first thing that happens is that it says that the file cant be oppened, even before it asks me for a name. That happens the first 3 tries and then the reading magically works.
I have bashed my head into this for the last two hours and I still cant understand what is happening. Can anyone please explain this to me, and show me my mistakes?
string input;
cout << "start writing and press enter to finish. It will be done better later." << endl;
cin>>input;
myFile << input;
In the lines above, cin>>input will stop reading at a space. You should use std::getline instead. See also this answer.