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

时间:2017-04-23 07:21:52

标签: c++ arrays

你好,这是我的代码:

#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 Sort\n2.Selection Sort\n3.Insertion Sort\n";
    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 ++的新手,并不熟悉语法,如何正确地将字符串转换为整数数组?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想要输入x ints以投入bubblesort并对它们进行排序。

您可以使用vector输入所需的整数,然后将vector复制到int array以与{bubblesort一起使用1}}。

它绝对不是排序的最佳方式,但似乎你是在练习它,所以这将是实现你想要的一种方式。

如果你愿意,我可以给你一个代码示例。让我知道。 此外,您的代码按原样分解。

为什么你首先想到使用String?

<强>代码

 vector<int> array;
 cout << "Enter numbers\n";
 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);

你已经完成了。 希望我能帮到你。 如果有人发现我的解决方案有任何问题,请发表评论