C++ 为什么我在printf遇到访问冲突?
调用堆栈如下: ucrtbased.dll!01905fcc未知 [下面的帧可能不正确和/或丢失,没有为UCRTBASE.dll加载符号] [外部代码] basketball.exe_VFPrPtffLIIOBFF * const流,conchchar * const格式,γ-CRTLLoalAlex指针* const x LoaLaar,char * AgListar线639 C++ basketball.exe!printfconst char*const\u格式。。。第954行C++ basketball.exe!主线81 C++ [外部代码]C++ 为什么我在printf遇到访问冲突?,c++,printf,access-violation,C++,Printf,Access Violation,调用堆栈如下: ucrtbased.dll!01905fcc未知 [下面的帧可能不正确和/或丢失,没有为UCRTBASE.dll加载符号] [外部代码] basketball.exe_VFPrPtffLIIOBFF * const流,conchchar * const格式,γ-CRTLLoalAlex指针* const x LoaLaar,char * AgListar线639 C++ basketball.exe!printfconst char*const\u格式。。。第954行C++ ba
在查看有人链接的其他帖子后,如果您使用printflow以下命令:%s,myString.c_str;,printf显然可以工作。.c_str允许以我最初尝试的方式使用它。谢谢你的帮助和链接。不知怎的,我早些时候错过了那个帖子 为什么。。。。。。。。。。。。。。。。。。。。printf?嗯,今天学到了一些新东西。将printf与字符串一起使用时存在未定义的行为,您可能正在为缺失的case块6、7、8等插入值。请改用std::cout。显然,用cout替换所有print f是可行的。但是为什么呢?您不能将cin/cout与scanf/printf混合使用吗?下面的操作正确。不能打开的箱子是玩家号码。这是一个不完整的LSU篮球花名册程序。基本上,您输入一个玩家号码,它会打印出拥有该号码的玩家的所有信息。基本上,整个程序通过使用cout更改所有printf实例来工作。那么,在使用case语句来决定字符串值时,是否可以不使用printf呢?或者在打印字符串时不能使用printf?@Rabbit84 printf是一个C函数。C不知道std::string是什么。这会使未定义的行为崩溃,在本例中表现为崩溃,因为%s告诉printf您将提供指向以null结尾的字符数组的指针。string不仅仅是一个字符数组。基本上,你把方形的钉子塞进了圆孔,printf太老太笨了,无法分辨两者之间的区别。谢谢,@Fang提供了另一篇文章的链接。
//I keep getting an access violation.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
string playername, hometown,position,height,Class;
int weight;
cout << "Enter player number: ";
cin >> x;
switch(x){
case 0: {
playername = "Brandon Sampson";
position = "Guard";
weight = 193;
hometown = "Baton Rouge, LA";
height = "6-5";
Class = "Sophomore";
break;
}
case 1: {
playername = "Dupo Reath";
position = "Forward";
weight = 235;
hometown = "Perth, Australia";
height = "6-10";
Class = "Junior";
break;
}
case 2: {
playername = "Antonio Blakeney";
position = "Guard";
weight = 197;
hometown = "Sarasota, Fla";
height = "6-4";
Class = "Sophomore";
break;
}
case 3: {
playername = "Elbert Robinton III";
position = "Center";
weight = 290;
hometown = "Garland, Texas";
height = "7-1";
Class = "Junior";
break;
}
case 4: {
playername = "Skylar Mays";
position = "Guard";
weight = 205;
hometown = "Baton Rouge, La";
height = "6-4";
Class = "Junior";
break;
}
case 5: {
playername = "Kieran Hayward";
position = "Guard";
weight = 195;
hometown = "Sydney, Australia";
height = "6-4";
Class = "Freshman";
break;
}
case 10: {
playername = "Branden Jenkins";
position = "Guard";
weight = 180;
hometown = "Maywood, Ill";
height = "6-4";
Class = "Junior";
break;
}
}
printf("Name: %s", playername);
printf("Position: %s\n", position);
printf("Height: %s", height);
printf(" Weight: %d", weight);
printf("Hometown: %s\n", hometown);
printf("Class: %s\n", Class);
return 0;
}