[英]Char to Int - C++
我知道已經有關於它的回答的問題,但是我已經閱讀了大多數問題,但仍然無法解決我的問題。 我有一個程序可以讀取筆記,將其保存在列表中,並為用戶提供刪除,更改或選擇特定筆記的選項。
我正在使用此結構:
struct List {
char title [101];
char text [501];
int cont; //code of the note.
struct List* next;
};typedef List list;
我被困在選擇點上,如果用戶鍵入*,則必須返回所有注釋,如果用戶鍵入數字,則必須僅返回對應的注釋。
到目前為止,我只是這樣:
List* select (List *l, int v) {
List *p = l;
for (p = l; p != NULL; p = p -> next){
if( p -> cont == v){
cout << "\nTitle: " << p -> title << "\n";
cout << "Text: " << p -> text << "\n";
cout << "Code: " << p -> cont << "\n" << "\n";
}
}
如何讀取char中的符號並將其轉換為int,以將其與注釋的代碼進行比較。
抱歉,如果我寫錯了,我是巴西人,我沒有寫作的習慣。
編輯:非常感謝你們,它確實對我有很大幫助,現在我可以完成我的工作! :d
嘗試這個:
以字符串形式獲取輸入
string str;
cin >> str;
如果字符串是*
if (str == "*")
{
// print out all notes
}
否則,也嘗試使用strtol將字符串轉換為數字。 Strtol比atol提供更好的錯誤檢查,因為它告訴您整個字符串是否已轉換,如果不轉換,那么可以在哪里查看。
char * endp;
long code;
code = strtol(str.c_str(), // the string converted to characters
&endp, // where in the string the number ended.
10); // the base of the number, base 10 in this case for
// decimal. 16 if you want to input in hex.
// Unlikely in this case.
if (*endp == '\0') // If the number didn't end didn't end at the end
// of the string, the number is invalid
{
// print note for code
}
快速了解 strtol(str.c_str(), &endp, 10);
和測試 endp
。
這實際上是行不通的。 endp
最后指向的內存位置在您檢查時可能無效。確實,您需要將char數組從字符串中取出並放入可以保證范圍的對象中。
基於舊的或錯誤的數據,以上警告不正確。 謝謝@TamásSzabó。 使將來的代碼編寫變得更簡單。
沒有std :: string版本幾乎相同:
char str[64]; // allocate storage for a big number.
cin.get(str, sizeof(str)); // read up to size of string -1 and null terminate
if ((str[0] == '*') && (str[1] == '\0'))
// first character in string is '*' and there
// is no second character
{
// print out all notes
}
else
{
char * endp;
long code;
code = strtol(str,
&endp,
10);
if (*endp == '\0') //this time endp will be valid
{
// print note for code
}
}
如果確實只需要char
和int
類型,則可以嘗試以下操作:
char buf[10]; // Assuming that you won't have more than 10 characters in your number
char *endp;
cin >> buf; // This may cause you problems if the input string is more than 9 characters long!
從這里開始,您可以使用user4581301的答案:
if ( (buf[0] == '*') && (buf[1] == '\0') )
{
// Print all your notes here
}
code = strtol(but, // the string converted to characters
&endp, // where in the string the number ended.
10); // the base of the number, base 10 in this case for
// decimal. 16 if you want to input in hex.
// Unlikely in this case.
if (*endp == '\0') // If the number didn't end didn't end at the end
// of the string, the number is invalid
{
// print note for code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.