so, i have this code. i have some questions about it, im at the beggining of learning c++.
My questions are:
how can i read more than one name in scanf ?
or when i want to read a street name [strada], eg: 1 northwood 34/6, when i insert space it passes the line and gets on next line, what i need to change in order to work as i want?
and why i cant print my person when i initialise ?
thanks
//create a struct which represent a person and that person must contain
//firstname lastname age, and adress. adress must contain street city and
//country
//define a function which it will be used for reading a person from keyboard. //define a function which will initialise a person.
//create a function which it will be used for releasing allocated resources for a person.
//create a functon which it will be used for printing the data about a person
// read from the keyboard a collection of persons, arrange those persons decreasing by age using qsort.
#include "stdafx.h"
#include <malloc.h>
#include <stdlib.h>
#include <string>
using namespace std;
struct adresa{char* strada, *oras,*judet;};
struct persoana{char* nume, *prenume;int varsta;adresa adr; };
void trimNewline(char* str)
{
int len = strlen(str);
if (str[len - 1] == '\n')
{
str[len - 1] = '\0';
}
}
void citestePersoana(persoana* pers){
printf("Nume:");
scanf("%s", pers->nume);
printf("Prenume:");
scanf("%s", pers->prenume);
printf("Varsta:");
scanf("%d", pers->varsta);
}
void citesteAdresa(adresa* adr){
printf("Strada:");
fgets(adr->strada, 100, stdin);
trimNewline(adr->strada);
printf("Oras:");
fgets(adr->oras, 100, stdin);
trimNewline(adr->oras);
printf("Judet:");
fgets(adr->judet, 100, stdin);
trimNewline(adr->judet);
}
void initPersoana(persoana* pers){
pers->nume = (char*)malloc(100 * sizeof(char));
pers->prenume = (char*)malloc(100 * sizeof(char));
pers->varsta = (int)malloc(100 * sizeof(int));
}
void initAdresa(adresa* adr){
adr->strada = (char*)malloc(100 * sizeof(char));
adr->oras = (char*)malloc(100 * sizeof(char));
adr->judet =(char*)malloc(100 * sizeof(char));
}
void afispers(){
persoana x;
adresa y;
printf("Nume:%s", x.nume);
printf("Prenume:%s", x.prenume);
printf("Varsta:%s", x.varsta);
printf("Strada:%s", y.strada);printf("Oras:%s", y.oras);
printf("Judet:%s", y.judet);
}
int _tmain(int argc, _TCHAR* argv[]){
persoana persoanaCurenta;
adresa adresaCurenta;
initPersoana(&persoanaCurenta);
initAdresa(&adresaCurenta);
citestePersoana(&persoanaCurenta);
citesteAdresa(&adresaCurenta);
afispers();
return 0;
}