This is for a project and this is only a single piece of the entire program that I'm hung up on.
I am being given a file where the format of the information is:
200707211245 F70.5
The numbers before the space are the YYYYMMDDTTTT T=time and I have to output to a new file in the format:
21.38 C --- recorded on 07/21/2007 at 12:45
This is fairly straight forward process, but I can't figure out how to change the first 7 numbers into an integer that I can pass to a function to format the date and time correctly. I am using Visual Studio 2013.
Subsequently this is all I've been able to do. Any and all help would be greatly appreciated. I'm getting an error over the .c_str() portion of the code.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream inFile;
inFile.open("inputData.txt", ios::in);
ofstream oFile;
oFile.open("results.dat", ios::out);
int date = atoi(inFile.c_str());
return 0;
}
int getDate(int date)
{
}
First some notes:
atoi return and int value, your number 200707211245 have 12 digits (int range is –2,147,483,648 to 2,147,483,647, ten digits max), your number don't fit in the type range, you would obtain strange results.
Better to use lexical_cast from boost
Here is an example:
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
int get_date(long long date) {
std::cout << date << std::endl;
return date;
}
int main()
{
ifstream in_file("H:\\save.txt", ios::in);
if (!in_file.is_open())
return -1;
std::string date_str;
in_file >> date_str;
int date1 = atoi(date_str.c_str()); // would overflow
long long date2 = boost::lexical_cast<long long>(date_str);
get_date(date2);
return 0;
}
Expected output:
200707211245
The simplest way to solve this problem is to parse the string input into separate strings for Y, M, D, H, M and temp. Read a line of input and divide it into pieces. You probably don't want to use Boost for a class. Just use std::string and the string operations in the standard library.
Then you can convert those little strings into little integers if you like, or just reformat them blindly into the output.
The temperature string will have to be converted to double in order to convert to Celsius.
Related
I'm trying to use "scanf" to read a string line: "is it not working", but I don't know if it's even possible to implement it in this particular example.
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "Just an example of, why ";
int number;
double doub;
string longText;
scanf("%d %lf %s", &number, &doub, &longText); //Read a line ex ("is it not working")
printf("%d\n%lf\n%s", number+i, doub+d,s+longText); //Print all the values, but not printing s+longText
}
Image showing the code
%s in printf/scanf family stands for char array, not std::string. If you want to get line, use std::getline. If you want to use std::string buffer for stdio functions, use std::string::data function, but I wouldn't suggest that as buffer-overflow is likely, especially for something like get-line.
First, I would like to express that I come to post my question, after a lot of searching on the internet, without finding a proper article or solution to what I'm looking for.
As mentioned in the title, I need to convert an ASCII file to Binary file.
My file is composed of lines, every line contain float separated by space.
I found that many people use c++ since it's more easy for this kind of task.
I tried the following code, but the generated file is so big.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
char buffer;
ifstream in("Points_in.txt");
ofstream out("binary_out.bin", ios::out|ios::binary);
float nums[9];
while (!in.eof())
{
in >> nums[0] >> nums[1] >> nums[2]>> nums[3] >> nums[4] >> nums[5]>> nums[6] >> nums[7] >> nums[8];
out.write(reinterpret_cast<const char*>(nums), 9*sizeof(float));
}
return 0;
}
I found those 2 resources :
http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html
https://r3dux.org/2013/12/how-to-read-and-write-ascii-and-binary-files-in-c/
I appreciate if you have any others resources ?
lines in my ASCII input file are as below :
-16.505 -50.3401 -194 -16.505 -50.8766 -193.5 -17.0415 -50.3401 -193.5
Thank you for your time
Here is a simpler method:
#include <iostream>
#include <fstream>
int main()
{
float value = 0.0;
std::ifstream input("my_input_file.txt");
std::ofstream output("output.bin");
while (input >> value)
{
output.write(static_cast<char *>(&value), sizeof(value));
}
input.close(); // explicitly close the file.
output.close();
return EXIT_SUCCESS;
}
In the above code fragment, a float is read using formatted read into a variable.
Next, the number is output in its raw, binary form.
The reading and writing repeat until there is no more input data.
Exercises for the reader/OP:
1. Error handling for opening of files.
2. Optimize the reading and writing (read & write using bigger blocks of data).
I have this program and I want to fill the tables array with the values passed from the command line in integer form . However It string s is only being assigned argument 6 .. what is the problem ?
#include <iostream>
#include <cctype>
#include <locale>
#include <cstdlib>
#include <sstream>
#include <string>
using namespace std;
int main(int argc,char *argv[]){
int i;
int tables[100];
stringstream str;
string s;
int result;
char value;
if(argc <=1){
cout<<"NO ARGUMENTS PASSED"<<endl;
exit(0);
}
/*char value = *argv[1];
cout<<value<<endl;
str << value;
str >> s;
result = stoi(s,nullptr,10);
cout<<result<<endl;*/
for (i=1;i<argc;i++){
if(isdigit(*argv[i])){
value = *argv[i];
str<<value;
str>>s;
cout<<s<<endl;
tables[i-1] = stoi(s,nullptr,10);
}
}
}
isdigit function test if a char is a digit, so the command line
isdigit(*argv[i])
Return true is the firts character of the char* is a digit. What you want is to convert a char* to an integer, I suggest to take a look at the atoi function.
However, the string convertion for printing your result is not necessary.
The problem is that you are using stringstream in the wrong way.
By writing str >> s you are reaching eof in the stream.
To fix this, you can avoid to use stringstream and instead directly assign value to s.
If you want to use stringstream, you can reset it back to initial state after writing to s as follows:
str.str(std::string{});
str.clear();
and use it again
My program will prompt user to input numbers and the program will calculate the multiplication of the numbers. I want to store my data into a csv file in this format
""00:01AM/02/05/14.csv""
This is to ensure that I can store my data into a new .csv file instead of the existing one each and every time I terminate my program.But my program is not outputting into a csv file due to some error that I could not fix.Im not sure what is causing this problem.
Here is my code :
#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>
#include <string>
#include <sstream>
#include <time.h>
using namespace std;
string get_time();
string get_date();
int main()
{ //I can compile the codes but it is not outputting into a csv file
string date,time,out;
float a,b,c;
ifstream indata;
ofstream outdata;
date=get_date();
time=get_time();
time=time+'/';
out=time+date;//combines data&time into 12:01AM/02/05/14.csv string form
cout<<out<<endl;
//outputs the data into a csv file--but it is not working
outdata.open(out.c_str());
outdata << "Num1,Num2,Answer" << endl;
while (!(a ==-100))
{
cout<<"Enter Num1:";
cin>>a;
if(a==-100)break;
cout<<"Enter Num2:";
cin>>b;
c=a*b;
outdata<<a<<","<<b<<","<<c<< endl;
}
system("pause");
return 0;
}
string get_date()//converts date to string
{
time_t now;
char the_date[15];
the_date[0] = '\0';
now = time(NULL);
if (now != -1)
{
strftime(the_date,15, "%d/%m/%y.csv", gmtime(&now));
}
return string(the_date);
}
string get_time()//converts time to stirng
{
time_t currtime;
struct tm * timeinfo;
char the_time [12];
time (&currtime);
timeinfo = localtime (&currtime);
strftime (the_time,12,"%I:%M%p",timeinfo);
return string(the_time);
}
Did you know that slash is a character that you cannot use in filenames? Slash aka '/' is the directory separator.
Even on Windows, because Windows tries to be at least a little bit compatible with Unix.
Also, this is a good lesson for you. Always check for error codes. You should have a check to see if your outdata.open succeeded.
i want to extract number string values of a char array. Actually I want to extract numbers embeded in file names for some file management. For example if there is a file name as file21 then i want the decimal number 21 from this file name.
How can i extract these values?
I tried the following but it results in an unexpected value. I think it is as a result of the implicit typecasting from the char to int while doing the arthimetic operation.
char * fname;
cout<<"enter file name";
cin>>fname;
int filenum=fname[4]%10+fname[5];
cout<<"file number is"<<filenum;
NOTE:
The filenamse are strictly in the format fileXX, XX being numbers between 01 and 99
You need to subtract '0' to get the decimal value of a digit character:
int filenum=(fname[4]-'0')*10+(fname[5]-'0');
Better yet, you should use atoi:
int filenum = atoi(fname+4);
You're getting undefined behavior because you're never allocating memory for the char* you read into:
char * fname = new char[16]; //should be enough for your filename format
or better yet
char fname[16];
Also, what do you expect:
fname[4]%10+fname[5];
to do? Magically concatenate the numbers?
First, you convert the first char to an int, multiply it by 10, convert the second char to an int and add to the first one. A simple google search for char to int would get you there.
How can i extract these values?
There are an infinite number of ways. One way is to use std::istringstream:
#include <string>
#include <sstream>
#include <iostream>
int main () {
std::string fname;
std::cout << "Enter file name: ";
std::getline(std::cin, fname);
int filenum;
std::istringstream stream(fname.substr(4,2));
if(stream >> filenum)
std::cout << "file number is " << filenum << "\n";
else
std::cout << "Merde\n";
}
Here is the simplest code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int filenum;
string fname;
cout<<"enter file name";
cin>>fname;
string str2 = fname.substr(4,2);
istringstream(str2) >> filenum;
cout<<"file number is"<<filenum;
return 0;
}
If your input is that much defined, the simplest solution is scanf:
int main()
{
int theNumber = 0;
scanf("file%d.txt", &theNumber);
printf("your number is %d", theNumber);
}
Check it out in action, reading from char* instead of stdio: http://codepad.org/JFqS70yI
scanf (and sscanf) also throws in checking for proper input format: returns number of fields read successfully. In this case if return value is any other than 1, the input was wrong.