C 将字符串转换为整数数组
C++ Convert String To Integer Array
你好,这是我的代码:
#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
array
与bubblesort
一起使用。
绝对不是对某些东西进行分类的最佳方法,但是,似乎您正在练习中,这将是实现自己想要的一种方法。
如果您愿意,我可以给您一个代码示例。让我知道。另外,您的代码被打破了。
您为什么首先想到使用字符串?
代码
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);
你完成了。希望我能帮助你。请如果有人看到我的解决方案有任何错误,请评论
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组