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.
Related
I have written this code to make a file with current date. It is working 100 percent fine but is this approach right? or is this solution optimum? Can anyone help me to come up with better solution if required?
What I have done here in this code.
Firstly I wrote date in a file named name.txt.
Then I read that file using getline function and stored in string variable s.(I used getline to make date in a single string)
Then I removed name.txt, because now it is useless.
Now I made a new file using c_style string s.c_str() and wrote something in file.( Note: s is a string variable containing date. )
Finally, I opened that file using s.c_str() to read the data in file.
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//SHAKAS ULTIMATE CODE
int main()
{
string s;
time_t now = time(0);
tm *ltm = localtime(&now);
ofstream file;
file.open("name.txt");
if(file.is_open())
{
file<< ltm->tm_mday<<"-";
file<<1 + ltm->tm_mon<<"-";
file<<1900 + ltm->tm_year;
//file<<1 + ltm->tm_hour<<"_"; Uncomment it if you want hours/min/sec on the name of file
//file<<1 + ltm->tm_min<<"_";
//file<<1 + ltm->tm_sec;
}
else
cout<<"Unable to create file";
file.close();
ifstream i;
i.open("name.txt");
while(!i.eof())
{
getline(i, s);
}
i.close();
remove("name.txt");
ofstream fileC;
fileC.open(s.c_str()); //writing in file, just to check
fileC << "WHO IS THE BOSS...?";
fileC.close();
string a;
i.open(s.c_str());
while(!i.eof())
{
getline(i, a); //Opening that file again to check if its written
cout<<a;
}
i.close();
}
I have the following code which compiles properly:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "INVESTMENT.h"
#include <vector>
using namespace std;
int main()
{
ifstream inputFile("jroth.csv");
string sHolder; //used as placeholder for string
float fHolder; //used as placeholder for float
double dHolder; ///used as placeholder for double
// while (inputFile.good())
vector<int> InvestVector; //will hold class (Investment) which contains string, double, and float
for (int i=0; i <= 7; i++)
{
Investment InvestVector[i]; //create new class for each line being pulled from .csv file
getline(inputFile, sHolder, ','); //pull in investment symbol as string
InvestVector[i].setSymbol(sHolder); //store string in the class
cout << InvestVector[i].getSymbol(); //verify string store properly
}
return 0;
}
As soon as the program runs, the executable crashes. Any thoughts on why?
Assuming you are using a C++ compiler with variable-length arrays, which is not standard C++, then this line:
Investment InvestVector[i];
creates an array with "i" places, numbered from 0 to i-1. Then these two lines:
InvestVector[i].setSymbol(sHolder);
cout << InvestVector[i].getSymbol();
will try to work with position number "i" of the array, that is, one past the end of the array.
So, I have a file that contains a pattern of a string then an int alternating line by line.
Something like this:
John McClane
30
James Bond
150
Indiana Jones
50
In this example, I would set John McClane to a string variable and then 30 to an integer variable. My issue is dealing with two types. I want to use getline(), but that only works with strings.
Is there an efficient or "right" way of doing this?
There are a number of approaches you could try.
Get string input, and convert to an integer if valid
Convert every second string to an integer
Try to read an integer when you expect one (just using cin >> in;). If you want a robust program, you can check validity with cin.good()
I don't know if there is a "right" way of doing this per say, but it's not a very taxing operation, so whatever you choose should be fine.
You could make a variable like this
string ibuf;
Then convert it to an integer doing this
getline(cin, ibuf);
(Whatever your int variable is) = strtol(ibuf.c_str(), NULL, 10);
One thing about C++ is that there are a large number of ways to accomplish any one task. One way to get integers from strings is to use a stringstream. There is a tutorial on stringstreams here
As for your problem with reading the alternating file, consider the following pseudocode:
boolean isInt = false;
while(fileIsNotOver) {
//getline
if(isInt) {
//use stringstream to get int here
} else {
//do whatever with the name here
}
isInt = !isInt;
}
I don't know if this fully works as i didn't tested it however it just compiles fine and answer should be something like this i think.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int counter = 0;
int number;
string test_string;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,test_string) )
{
cout << test_string << '\n';
++counter;
if(counter % 2 == 0 ){
number = atoi(test_string.c_str());
cout << number << '\n';
}else{
cout << test_string << '\n';
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
You can try like this to read a string then an int alternating line by line.
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int main()
{
string name;
int number;
freopen("input.txt", "r", stdin);
while (getline(cin, name))
{
cin >> number;
/*
process the input here
...
...
*/
getline(cin, name); // just to read the new line and/or spaces after the integer
//getchar(); //you can use getchar() instead of getline(cin, name) if there is no spaces after the integer
}
return 0;
}
Thanks !!!
I am c++ beginner and this is for school..
I am trying to read a file about 28kb big. The program works but it doesnt print the first 41 lines. It works fine with a smaller file.
At first i was reading into a char array and switch it to strings.
i also tried changing the log buffer but it apparently it should be big enough..
I feel like this should be very simple, but just cant figure it out..
Any help will be greatly apreciated..
Thanks!
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cerrno>
using namespace std;
struct espion
{
char nom[30];
char pays[20];
char emploi[29];
};
int main()
{
const int MAX_NOM = 30, MAX_PAYS = 20, MAX_EMPLOI = 29;
char nomFichier[50] = "espion.txt";
ifstream aLire;
aLire.open(nomFichier, ios::in|ios::binary);
if(!aLire.is_open()){
exit(EXIT_FAILURE);
}
std::string infoEspion;
while(aLire)
{
infoEspion.clear();
std::getline(aLire, infoEspion);
cout << infoEspion ;
}
aLire.close();
system("pause");
return 0;
}
From the system("pause"), it looks like you're running on Windows. With ios::binary, the end-of-line marker is not translated, and the cout << infoEspion; statement prints these "raw" lines in such a way that all of the lines are written on top of each other. (More specifically, each line will end with a return but no newline, so the cursor goes back to the start of the same line after executing each cout statement.) If you take out the ios::binary, you will echo all of the input on a single, very long line. Changing the statement to cout << infoEspion << endl; will echo all of the lines.
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.