繁体   English   中英

C++ /// 如何使用 for 和 if 循环将值附加到 int 变量

[英]C++ /// How do i append a value to an int variable with for and if loop

正如标题所说,我目前对如何将字符数组中的值附加到 Int 变量感到困惑。 我知道如何在 python 中解决这个问题,但我对 C++ 真的很陌生,我一直在尝试在线寻找解决方案,但没有任何解决方案。

所以无论如何这是我的代码

#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;


int main()
{
    char studentId[9];
    cout << "Enter Student ID : ";
    cin >> studentId

    int n;
    cout << "\nYour special number is ";
    for (n=1; n<(sizeof(studentId)); n+=2)
    {
        cout << studentId[n]; //this displays all numbers in even places, this one works
    }


    char oddId[8];
    for (int c = 0; c < 8; c++)
    {
        if (studentId[c] % 2 != 0)
        {
            oddId[c] = studentId[c];
        }
    }
    cout << "\nOdd numbers after the for loop : " << oddId;
    int oddInt = stoi(oddId);
    cout << "\nOdd numbers after converted to Int : " << oddInt; // i need to convert the odd numbers to int so i can get the remainder
    cout << "\nYour lucky number is " << oddInt % 9 << endl; //remainder of odd numbers when divided by 9


    return 0;
}

这是输出

输出

非常感谢您,已经尝试解决这个问题 3 天了。

[编辑]

这就是我在 python 中所做的,可能是一团糟,但它的工作方式是我想要的:

def magic(num_list):
s = ''.join(map(str, num_list))
return(int(s))

std_id = input("Enter Student ID: ")

id_list = []
for a in std_id:
    id_list.append(a)

id_no = list(map(int, id_list))

even_list = id_no[1::2]

odd_list = []
for x in id_no:
    if x % 2 == 1:
        odd_list.append(x)

oddodd = magic(odd_list)
eveneven = magic(even_list)

print("Your special number is", eveneven)
print("Your lucky number is", oddodd % 9)

这部分代码有几个问题:

char oddId[8];
for (int c = 0; c < 8; c++)
{
    if (studentId[c] % 2 != 0)
    {
        oddId[c] = studentId[c];
    }
}

首先, oddId不够大。 要保存 8 位字符串,您需要 9 个元素,因为您需要一个空终止符。

其次,您对输入数组和输出数组使用相同的索引c 这意味着对应于oddId偶数元素的studentId元素将永远不会被填充。这就是为什么您会在输出中间看到所有这些垃圾字符的原因。

第三,完成后永远不要添加空终止符。 这就是为什么您会在输出末尾看到更多垃圾字符的原因。

第四,如果输入字符串的长度小于 8 个字符,您将读到它的末尾。 您需要使用strlen()来获取限制。 您还应该在打印所有偶数位置的较早循环中使用它,而不是sizeof(studentId)

尝试这个:

char oddId[9];
int indexout = 0;
int len = strlen(studentId);
for (int indexin = 0; indexin < len; indexin++)
{
    if (studentId[indexin] % 2 != 0)
    {
        oddId[indexout++] = studentId[indexin];
    }
}
oddId[indexout] = '\0';

顺便说一句,如果您使用std::string而不是 C 样式的字符串,事情会容易得多,因为它支持连接。

int value = 0;
for(int ndx = 0; count != ndx; ++ndx)
{
  value *= 10;
  value += str[ndx] - '0';
}

假设长度已知并且所有字符都在 0 和 9 之间(包括 0 和 9)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM