2017-04-23 59 views
-2

您好,这是我的代码:C++字符串转换为整数数组

#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 + +,并没有真正熟悉的语法,如何正确地将字符串转换为整数数组?

+0

您的代码按原样被打破。 'main'函数和'switch'语句不完整。 – InternetAussie

+0

我只拿这些,代码,因为我只是想评估一下情况1 –

回答

0

如果我理解正确,您希望得到x ints的输入,并将其输入bubblesort并对它们进行排序。

可以使用vector,输入你想要的许多整数,然后你可以复制vectorintarraybubblesort使用。

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

我可以给你一个代码示例,如果你喜欢。让我知道。 此外,您的代码按原样打破。

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

代码

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); 

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

+0

ohhhhhhh的bubblesort,所以有这个“矢量”,你能给我一个如何做到这一点的例子吗?我认为将字符串转换为一个整数数组可以完成这项工作,所以我可以将它们排列在冒泡排序中,是的,即时通讯是为了练习。我在python和java中写了这个,但是不能在C++中找到它。 –

+0

@JedHart查看我更新的答案 –