Char to Int - C++

Char to Int - C++

本文关键字:C++ Int to Char      更新时间:2023-10-16

我知道已经回答了有关它的问题,但是我已经阅读了其中的大多数,但仍然无法解决我的问题。我有一个程序,可以阅读笔记,将其保留在列表中,并为用户提供选项以删除,更改或选择特定的注释。

我正在使用此结构:

struct List {
    char title [101];
    char text  [501];
    int cont; //code of the note.
    struct List* next;
};typedef List list;

我陷入了选择点,如果用户类型a *它必须返回所有注释,如果用户类型A号码必须仅返回相应的注释。

到目前为止,我只有这个:

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 Too将字符串转换为数字。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 == '') // 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指向内存位置,该内存位置可能在您进行检查时可能无效。确实,您需要将字符阵列从字符串中取出并保证范围的东西。

基于旧的或错误的数据,上述警告是不正确的。谢谢 @tamásszabó。使未来的代码写作更简单。

no std ::字符串版本几乎相同:

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] == ''))
                   // 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 == '')  //this time endp will be valid 
    {
        // print note for code
    }
}

如果您确实需要charint类型,则可以尝试以下操作:

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] == '') )
{
 // 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 == '') // If the number didn't end didn't end at the end 
                   // of the string, the number is invalid
{
    // print note for code
}