Reputation: 3
i met an weird problem:first i need scanf function to input a special stream,like this:scanf("%s %4d/%2d/%2d", &temp.name, &temp.year, &temp.month, &temp.day);
,the type of temp is a struct which conclude four variable:
struct citizen{
char* name;
int year;
int month;
int day;
}
actually i use string type instead of char *, but scanf seem not to support it. i creat an vector, and push temp into this vector, when i end up my input task, i want to output the variable:name of the struct, but program always goes wrong and break down, there is my full code as follows:
#include <iostream>
//#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
struct citizen{
char* name;
int year;
int month;
int day;
bool operator < (const citizen &A) const{
return (year*365+month*30+day) < (A.year*365+A.month*30+A.day);
}
};
int main(){
int n;
cin >> n;
vector<citizen> ci;
citizen temp;
int bb = 2014*365+9*30+6;
for(int i = 0; i < n; i++){
scanf("%s %4d/%2d/%2d", &temp.name, &temp.year, &temp.month, &temp.day);
bool p = 1;
int bt = temp.year*365+temp.month*30+temp.day;
if(bt>bb)
p = 0;
else if((bb-bt) > 200*365)
p = 0;
if(p)
ci.push_back(temp);
}
printf("%s", ci[0].year); //1st method to ouput
for(vector<citizen>::const_iterator it = ci.begin(); it != ci.end(); it++) //2nd method to ouput
cout << it->name;
//but both goes wrong
return 0;
}
any idea?
Upvotes: 0
Views: 175
Reputation: 409206
With the statement
scanf("%s %4d/%2d/%2d", &temp.name, &temp.year, &temp.month, &temp.day);
you have two major problems:
When scanning for strings, the scanf
function expects a pointer to the first character, which should be of type char*
. You pass &temp.name
which is a pointer to the pointer and is of type char**
.
Once you fix that, the pointer you pass with temp.name
is pointer to... I don't know, and neither do you. It is uninitialized, will have an indeterminate and seemingly random value. You need to use an array of characters instead, or allocate memory dynamically and assign the result to the pointer.
Of course, this wouldn't be a problem at all if you used standard C++ input with std::cin
and std::string
instead.
Upvotes: 1