I have made a program that reads value from txt file "database.txt", but output is wrong when the number is three digit
ifstream myfile("database.txt");
int broj_rijeci = 0;
if (myfile.is_open())
{
while (getline(myfile, line))
{
if (line.at(0) == '[')
{
int i = line.length() - 2;
int brojac = 0;
system("pause");
while (line.at(i) != line.at(0))
{
input = line.at(i);
ascii_convert(input);
broj_rijeci = broj_rijeci + input * pow(10, brojac);
i--;
brojac++;
}
}
}
myfile.close();
}
else cout << "Unable to open file";
and my database looks like this:
[311]
output is "310"
The algorithm for opening and reading a text file in C has given below: Assign file pointer to fopen () function with write format The above source code is simple to understand and friendly due to the use of multiple comment lines.
I'm experiencing issues with Data Import From Text/CSV where the import Wizard is incorrectly truncating columns and not importing all the data. To replicate: 1. In Excel select the "Data" menu from the ribbon 2. Click "From Text/CSV" 3. Browse and select the file to import (use a file with say 20 items per row, separated by your chosen delimiter.
This c program is used to read the text file line by line and we need to parse the format of each line in the file to required formats. fgets function is used to read string from text file till max characters in each line in file.
Algorithm for Opening and Reading the text file 1 Start 2 Declare variables and file pointer 3 Open the file 4 If the file is not opened print error massage 5 Print the content of the text file using loop 6 Close the file 7 Stop
Since you haven't provided the implementation of ascii_convert
it's difficult to tell if the problem is there or elsewhere. However you can greatly simplify the process and eliminate the need for your own conversion routines by using std::stringstream
.
#include <sstream>
std::ifstream myfile("database.txt");
if (myfile.is_open())
{
std::string line;
while (std::getline(myfile, line))
{
if (line.size() > 1 && line[0] == '[' && line[line.size() - 1] == ']')
{
int value;
if(std::istringstream(line.substr(1, line.size() - 2)) >> value)
{
// Conversion was a success ... do something with "value"
}
else
{
// Conversion failed. Handle error condition.
}
}
}
myfile.close();
}
else std::cout << "Unable to open file";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With