C 将字符串转换为整数数组

C++ Convert String To Integer Array

本文关键字:整数 数组 转换 字符串      更新时间:2023-10-16

你好,这是我的代码:

#include<iostream>
#include <stdio.h>
#include <math.h>
void bubbleSort(int ar[]);
using namespace std;
int main()
{
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;

    int choice;
    std::cout << "nWelcome to the algortihm tester!n";
    std::cout << "What algorithm would you like to test?";
    std::cout << "nChoose: n1.Bubble Sortn2.Selection Sortn3.Insertion Sortn";
    scanf("n%d", &choice);
    switch(choice)
    {
    case 1:

        std:: string trash;
        std::string str;
        std::cout << "nINPUT:";
        std::getline (std::cin,str);
        std::getline(std::cin,trash);
        int* myarray = new int[str.size() ];
        std::copy( str.begin(), str.end(), myarray);
        bubbleSort(myarray);
        break;
    }
}

void bubbleSort(int myarray[])
{
    int length = sizeof(myarray)/sizeof(myarray[0]);
    int i;
    for(i=(length-1); i >= 0; i--)
    {
        for(int j =1; j<=i; j++)
        {
            if (myarray[j-1]>myarray[j])
            {
                int temp = myarray[j-1];
                myarray[j-1]=myarray[j];
                myarray[j]=temp;

            }
        }
    }
}

我正在尝试制作一个程序,该程序接受用户,字符串的输入,然后将其复制到数组中,然后将数组传递到函数bubbleSort。但是,当我运行它时,我将结果称为0,这意味着,字符串未正确复制到数组。我是C 的新手,对语法并不真正熟悉,我该如何正确地将字符串转换为整数数组?

如果我正确理解,您想获得x ints的输入以扔进 bubblesort并对其进行排序。

您可以使用vector,输入所需的整数,然后可以将vector复制到int arraybubblesort一起使用。

绝对不是对某些东西进行分类的最佳方法,但是,似乎您正在练习中,这将是实现自己想要的一种方法。

如果您愿意,我可以给您一个代码示例。让我知道。另外,您的代码被打破了。

您为什么首先想到使用字符串?

代码

 vector<int> array;
 cout << "Enter numbersn";
 int tmp;
 while (cin >> tmp)
     array.push_back(temp);

while (cin >> tmp)

此行在这里,将其下方的线循环,直到给出一个不是int的值。之后,您做类似的事情。

int *arr = new int[array.size()];
std::copy(v.begin(), v.end(), arr);

你完成了。希望我能帮助你。如果有人看到我的解决方案有任何错误,请评论