gpt4 book ai didi

c++ - 获取 : "STATUS_ACCESS_VIOLATION" when attempting to compile this C++ code

转载 作者:行者123 更新时间:2023-11-28 06:23:04 26 4
gpt4 key购买 nike

可能是什么问题?我认为这可能是在我使用 strtok 时初始化指针,但这并没有解决问题。对不起,如果这很愚蠢,我对此很陌生。

这是我的代码:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
using namespace std ;

int main() {

//initialize and get input into a string, turn into a cstring
string intstring ;
cout << "Enter five integers: " ;
cin >> intstring ;
char * cstr = new char [intstring.length()+1];
strcpy (cstr, intstring.c_str());

//use strtok to convert into an array of strings
int intarray[5] ;
char * point = strtok ( cstr , " " ) ;;
int i = 0 ;
while ( point != NULL ) {
intarray[i] = atoi ( point ) ;
point = strtok ( cstr , " " ) ;
i++ ;
}

//get the sum of all integers
int sum = 0;
for (int i = 0; i < 5 , i++ ;) {
sum += intarray[i] ;
}

//sort the array of integers
sort(intarray, (intarray + 5)) ;

//print the mean and median
cout << "Median is " << intarray[2] << endl;
cout << "Geometric mean is " ;
cout << (sum / 5) << setprecision(4);

return (0) ;
}

最佳答案

两个错误是:

  • cin >> intstring 只读取第一个数字,在找到空格时停止。您希望 getline(cin, intstring) 读取整行
  • 只有对 strtok 的第一次调用才应将 cstr 作为参数传递。后续调用应传递 NULL 以从上次调用结束处继续。您一直读取第一个值,直到 i 超出范围并导致崩溃(或其他未定义的行为)。

但是,因为这是 C++ 而不是 C,所以真的不需要 strtok。从输入中读取五个数字的简单方法是

for (size_t i = 0; i < 5; ++i) {
cin >> intarray[i];
}

关于c++ - 获取 : "STATUS_ACCESS_VIOLATION" when attempting to compile this C++ code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com