2017-04-23 55 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查看我更新的答案 –