20-06-2005, 16:58
|
|
|
חבר מתאריך: 29.04.04
הודעות: 638
|
|
כל נסיונותי להפוך מחרוזת למספר עולים בתוהו
שלום !
ברצוני לחלץ מספר ממחרוזת אך הדבר לא עולה בידי.
להלן 4 אפנים בהם ניסיתי לבצע והשגיאות שהעליתי בחכתי:
נסיון 1, דרך מצביע למערך:
קוד:
#include <cstdlib>
#include <iostream>
using std::cout;
#include <string>
using std::string;
#include <cstring>
int main()
{
char *myDrink = "Coffee 4 2";
int myD4 = myDrink[7];
cout << "\nmyD4 is: " << myD4; // i get 52 !
return 0;
אני מקבל 52 במקום 4 !
נסיון 2, מערך מסוג char
קוד:
char yourDrink[10] = "Coffee 4 2";
int yourD4 = yourDrink[7];
cout << "\nyourD4 is: " << yourD4; // i get 52 !
גם במקרה זה אני מקבל 52 במקום 4.
ניסיון מס. 3 עבודה עם משתנה מסוג string:
קוד:
string ourDrink = "Coffee 4 2";
int ourD4 = ourDrink.substr(7,1); // cannot convert 'string' to 'int'
המהדר מפיק את הודעת השגיאה הבאה: cannot convert string to int
ניסיון מס. 4: שימוש ב atoi:
קוד:
string ourDrink = "Coffee 4 2";
int ourD4 = atoi(ourDrink.substr(7,1)); // could not find a match to atoi
המהדר מפיק הודעת שגיאה: couldnt find a match to atoi
מישהו יכול לתקן את הקוד שכתבתי או להפנות אותי לסוג אחר של קוד באופן שאצליח לחלץ את המספר מהמחרוזת ?
תודה !
|