PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : C++: Name+Variable



expoman
13-06-2002, 16:45
Hi
Ich versuche gerade ein Prog zuschreiben, welches in einer for-Schleife einen Namen entgegennimmt und diesen unter "name+i" z.B. name3 abspeichert.
Ich hab keine Ahnung wie man die Zahl dahinter anfügt.

Danke im Vorraus

anda_skoa
13-06-2002, 18:15
Gibt vielleicht eine einfachere Möglichkeit, aber das sollte gehen:



#include <string>
#include <stdio.h>

int main (int argc, char* args[])
{
for (uint i = 0; i < 5; i++)
{
string input;
cin >> input;
char buffer[11]; // 10 Stellen+ terminierende Null
sprintf(&buffer[0], "%d", i);
string output = input + string(buffer);
cout << output << endl;
}
return 0;
}


Ciao,
_

tkortkamp
13-06-2002, 20:19
Hier noch eine Möglichkeit:



#include <string>
#include <iostream>
#include <sstream>

int main (int argc, char* args[])
{
for (int i = 0; i < 5; i++)
{
std::string input;
std::cin >> input;

std::stringstream stream;
stream << input << i;

std::cout << stream.str() << std::endl;
}
return 0;
}


Cu,
Tobias

anda_skoa
13-06-2002, 21:49
Ah, das ist sauber!

Auf stringstream hätte ich auch kommen können.

Ich bin schon zu Qt verwöhnt :D
Muß wohl meine Standardlib Kenntnisse wieder aufpolieren :rolleyes:

Ciao,
_

Vir@s
14-06-2002, 05:50
Und noch ne Möglichkeit mit Pointern:



#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#include <string.h>

int main(int argc, char *argv[]) {
char *name = (char *) malloc(20);

for(int i = 0;i < 5; i++) {
scanf("%s",name);
name = strcat(name, itoa(i," ",10));

printf("\n%s",name);
}

free(name);

return 1;
}


Mfg, Vir@s

expoman
14-06-2002, 14:39
!!!Super!!!Danke an euch alle
Ihr habt mir wirklich weiter geholfen

Werd dann mal weiter progen