Error modules with different cpu types were found

I'm getting the following runtime error in my WCF service. Could not load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system

I’m getting the following runtime error in my WCF service.

Could not load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

After some looking around, I found a suggestion to use Assembly Binding Log Viewer, or Process Monitor. Neither or which yielded any information (that is, the log viewer showed nothing at all, and the process viewer didn’t see the assembly load being attempted.

I finally came across a suggestion to use this utility (dependency walker) to find out what the assembly was actually looking for. On opening, I got an error immediately; and the log stated the following:

Error: Modules with different CPU types were found.
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

Error: Modules with different CPU types were found.
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

According to the module list, it couldn’t find these:

API-MS-WIN-CORE-COM-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL
API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL
DCOMP.DLL
IESHIMS.DLL

Some of these look like they relate to the RT framework; however, this application was developed in .NET 3.5 (actually, that’s not strictly true — it was developed in 4.5 and downgraded to 3.5).

Looking at some of these files seems to imply they are quite core Windows files, and oddly, I have used this dll elsewhere in the solution (admittedly on the client) without issue.

I’m using VS2013 although I’ve tried VS2012 and get the same issue.

I did come across this question which at first glance seems to be the same, although it relates to C++.

Can anyone give me some guidance as to what the issue might be, or what to try next?

Here is my fusion log:

=== Pre-bind state information ===
LOG: DisplayName = MyAssembly.MyLib.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, processorArchitecture=MSIL (Fully-specified)
LOG: Appbase = file:///c:/myprog/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = myprog.exe
Calling assembly : System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:myprogbinDebugmyprog.exe.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:WindowsMicrosoft.NETFramework64v4.0.30319configmachine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).

I managed to reduce the library in question down until it was just a single static function that returns a string, and still get the error.

  • Remove From My Forums
  • Question

  • Some background, I am converting my program from x32 to x64 using visual studio 2008. After conversion, My program is unable to run. I did a dependency walker on the dll and discovered that Modules with different CPU types were found. The
    affected modules are Kernel32, GDI32,OLEAUT32,USER32.

    I am wondering if there is additional settings required after conversion to x64 to make it run. I am using mfc in the code as well.

Answers

  • You don’t convert a project from 32 to 64 bit. You add new x64 platform to existing 32-bit project. Try to do this.

    — pa

    • Proposed as answer by

      Wednesday, April 11, 2012 2:27 AM

    • Marked as answer by
      Helen Zhao
      Monday, April 16, 2012 2:19 AM

    • Edited by
      Selvam
      Tuesday, April 10, 2012 11:15 AM
    • Proposed as answer by
      Helen Zhao
      Wednesday, April 11, 2012 2:27 AM
    • Marked as answer by
      Helen Zhao
      Monday, April 16, 2012 2:19 AM

0xc000007b is one of many well-known runtime error codes. You can check out other error codes and their more user friendly descriptions here:

Link

Someone may correct or elaborate on this point but if we see code 0xc000007b, we are being told that a binary we tried use is either corrupt or not intended to be run in our process. That description is intended to be vague because this error code can cover a large number of situations. I would argue that there are no one-size-fits-all solutions to this problem but I will share ideas on how to track down the root cause of this issue. The root cause could vary from user to user and a case-by-case solution will be needed.


Why am I seeing this code?

The short answer is that I won’t know until I get more info from you. Often times, this error code is caused by a 64-bit process trying to use a 32-bit dll or vice versa. In our case, the 64-bit Launcher is probably trying to load a .dll that it wasn’t meant to run with. The problem is that this isn’t the only situation that could cause this error code. It could be a subtle problem with any of the binaries used/referenced. I’m not clear on all the ways users can get into this state but usually it has to do with dependencies that are corrupt, modified, incorrectly installed, or that have been tampered with. I’ll be sure to update my answer if/when I find out more.


How can I pinpoint the problem?

Some users have had luck uninstalling and then reinstalling some of the well-known dependencies(directx, VCRedist, etc). This is a hit or miss solution because we can’t be sure which of those dependencies, if any, is causing the problem without investigating further. This is a valid approach to the problem and you may get lucky but if you want to know more about the root cause of this problem we’ll need some tools:

Dependency Walker 2.2 x64


is a very useful tool for troubleshooting system errors related to loading and executing modules and we’ll use it here to see what module is causing our 0xc000007b error. There are many ways of using dependency walker to pinpoint the problem and you could experiment with the tool(be sure to check out the depends.chm documentation that is packaged with it). Note: If you are having difficulty viewing the documentation, you may need to Unblock it in the properties (right click depends.chm -> Properties -> General Tab -> Unblock). Below I run you through an example of using Dependency Walker on my Unreal Engine Launcher.


Using Dependency Walker

Here I intend to give you an overview of one of the ways you could use Dependency Walker to pinpoint the module that is causing issues. I had to tamper with one of my System Dlls to artificially reproduce the problem so your log files will be different but you’ll be generating and reading the logs in a similar way on your computer.

  1. Download Dependency Walker 2.2 x64 from here:

    Link

  2. Extract

    depends22_x64.zip

    to

    C:DWalker
  3. Open a command window as administrator (Start Menu -> type “cmd” in the search box and right click on cmd.exe and select Run as Administrator)
  4. Enter the following command to switch to the folder we extracted Dependency Walker to: cd C:DWalker
  5. Enter the following command to have the tool generate logs while running Unreal Engine Launcher(Note: I have my Unreal engine installed to the default location, you would replace c:Program FilesUnreal Engine in the command below with your install location):


    depends.exe /c /f:1 /pb /pp:1 /pg:1 /ot:Log.txt "c:Program FilesUnreal EngineLauncherEngineBinariesWin64UnrealEngineLauncher.exe"

  6. This will run Unreal Engine Launcher and you’ll see the familiar 0xc000007b error message. Click OK to dismiss it as usual.
  7. You should now have a Log.txt file in the C:DWalker folder. In the next section I’ll go over what to look for in this log to pinpoint the problem module.


Reading Dependency Walker Logs

If you followed the steps above, you should have a Log.txt file in your c:DWalker folder. Open the log in a text editor and have a look. If you are anything like me, and seeing one of these logs for the first time, the contents of the log may make your head spin. Use the points below as a guide when searching for errors. I’ll update this section whenever I find a different fail case. Note: Don’t get hung up on every little warning/error you spot in the log, Dependency Walker may generate many warnings and errors for an application but most of these will be harmless and can be ignored. If you feel comfortable doing so, I would encourage you to share your log so that we can spot any common issues and hopefully find a way to get them fixed up in future releases.

Search the log for the strings in bold:


  • Error: Modules with different CPU types were found

    . This means the 64 bit process was given a 32 bit module. To pinpoint the module having the problem, look through the list of DLLs before the error appeared and find the one with the [ E ]. Here is an example of my xinput dll having issues loading:

    [ E ] c:windowssystem32XINPUT1_3.DLL

  • Error: At least one file was not a 32-bit or 64-bit Windows module

    . This means a DLL is probably corrupt. To pinpoint the module having the problem, look through the list of DLLs before the error appeared and find the one with the [ ! ]. Here is an example of my xinput dll which is corrupt:

    [ ! ] c:windowssystem32XINPUT1_3.DLL

  • At least one module was corrupted or unrecognizable to Dependency Walker, but still appeared to be a Windows module

    . This means a module was invalid. To pinpoint the module(s) having the problem, look through the list of DLLs before the warning appeared and find any with [ ! ] or [ !6]. Here is an example of a module that has this issue:

    [ !6] c:windowssystem32D3DCOMPILER_43.DLL


What do I do once I pinpoint the problem?

First we’ll need to pinpoint the product the DLL is associated with and try to reinstall/repair that product. In my case, above, XINPUT1_3.dll is part of DirectX so I would download DirectX from a trusted Microsoft site and reinstall it. If the same issue shows up in the logs after I do that I would get more aggressive with my reinstall: I would backup my copy of the .dll, delete the original, try to reinstall again, and check to make sure a new copy of the dll was put in place. Note: Some people suggest to download DLLs from various websites but I want to caution you about this: I would personally never never never never… never use an untrusted site to download .dlls from. In other words,

do not use untrusted sites to download DLLs

.

SYSTEM:

Windows 7 Pro 64bit SP1

Intel Core i7 2600k

Asus P8P67 Deluxe

16 GB Ram

Micron M600 512GB SSD

PROBLEM

Long delays (35-50 seconds) when clicking on file in explorer, other applications crash.

ERROR MESSAGES ALWAYS INVOLVE MSVCR80.DLL

One error message was…

“Access violation at address 73AC73D0 in module ‘MSVCR80.dll’. 
Write of address 1003F300.”

DEPEDENCY WALKER (DW)

c:windowswinsxsx86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.6229_none_d089f796442de10eMSVCR80.DLL

DW indicated there were several 64 bit modules (API-MS-WIN-CORE-…) showing up as errors. 
There was only one 32 bit module as indicated above (….msvcr80.dll) and this one was not flagged as an error.

DW provided 2 error messages:

“ERROR: At least one module has an unresolved import due to a missing export function in an implicitly dependent module.”

“ERROR: Modules with different CPU types were found.”

ATTEMPTED SOLUTIONS

I have removed all C++ runtime entries in the Programs and Features window.

I have removed almost all MS Visual Studio entries. (Some are presenting errors when an attempt is made to remove)

MS Visual C++ 2012, 2013 and 2015 Redistributable (x64) and (x86) remain.

However, problem persists.

HOW CAN I CORRECT THE MIXED CPU TYPES LISTED IN THE MODULES?

using Windows 7 64bit sp1.
Visual Studio 2008 vc9
(got 64bit redistribution installed)

been googling for many hours , reinstalled opencv a few times , with different versions.

so far I found out that this error is caused by 32bit — 64bit encounter.

I downloaded Dependency Walker and checked my debug exe it had a few «cannot find» messeges
MSVCP80D.dll, MSVCR80D.dll , IESHIMS.dll and TBB_DEBUG.dll

so I tried to get those files into the project folder.
downloaded the first 3 and got the tbb_debug from the opencv folder

now i still have the 0xc000007b messege when trying to use the executeable
and the dependecny walker says the following:

Error: At least one module has an
unresolved import due to a missing
export function in an implicitly
dependent module. Error: Modules with
different CPU types were found.

and in the files list nothing that i can see where the problem is at
(no red lines no nothin!)

1 answer

I used to have the similar problem as you, but I finally solved it. I had that problem was because I set the environment variables PATH’s value as «……x64……»(for DLL) while my vs2013 is 32bit. So when I changed the x64 to x86, the problem was gone.

Question Tools

Related questions

Я получаю следующую ошибку времени выполнения в моей службе WCF.

Could not load file or assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

После некоторого осмотра я нашел предложение использовать Средство просмотра журнала привязки сборки или Монитор процессов. Ни то, ни другое не дало никакой информации (то есть средство просмотра журнала вообще ничего не показало, а средство просмотра процессов не увидело попытки загрузки сборки.

Наконец-то я наткнулся на предложение использовать эта утилита (обходчик зависимостей) чтобы узнать, что на самом деле искала сборка. При открытии я сразу получил ошибку; и в журнале было указано следующее:

Ошибка: Найдены модули с разными типами ЦП. Предупреждение. По крайней мере один модуль зависимостей отложенной загрузки не найден. Предупреждение. По крайней мере один модуль имеет неразрешенный импорт из-за отсутствия функции экспорта в зависимом от отложенной загрузки модуле.

Error: Modules with different CPU types were found.
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

Согласно списку модулей, он не смог найти следующие:

API-MS-WIN-CORE-COM-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL
API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL
DCOMP.DLL
IESHIMS.DLL

Некоторые из них выглядят так, как будто они относятся к фреймворку RT; однако это приложение было разработано в .NET 3.5 (на самом деле это не совсем так — оно было разработано в 4.5 и понижено до 3.5).

Глядя на некоторые из этих файлов, кажется, что они являются основными файлами Windows, и, как ни странно, я использовал эту dll в другом месте решения (по общему признанию, на клиенте) без проблем.

Я использую VS2013, хотя я пробовал VS2012 и получаю ту же проблему.

Я наткнулся этот вопрос который на первый взгляд кажется таким же, хотя и относится к C++.

Может ли кто-нибудь дать мне некоторое руководство относительно того, в чем может быть проблема, или что попробовать дальше?

Вот мой журнал слияния:

=== Pre-bind state information ===
LOG: DisplayName = MyAssembly.MyLib.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, processorArchitecture=MSIL (Fully-specified)
LOG: Appbase = file:///c:/myprog/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = myprog.exe
Calling assembly : System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:myprogbinDebugmyprog.exe.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:WindowsMicrosoft.NETFramework64v4.0.30319configmachine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).

Мне удалось уменьшить рассматриваемую библиотеку до тех пор, пока она не стала всего лишь одной статической функцией, которая возвращает строку и все еще получает ошибку.

  • Forum
  • General C++ Programming
  • .exe file crashes outside VS but work in

.exe file crashes outside VS but work inside

I have a program that works well inside visual studio when I launch it via local windows debugger, but when I open the .exe file, it outputs some stuff and takes some input, then it crashes at some moment when it should display other outputs. How can I fix this?
I ran Dependency Walker on the .exe file and it outputted this:

1
2
3
4
Error: At least one required implicit or forwarded dependency was not found.
Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module.
Error: Modules with different CPU types were found.
Warning: At least one delay-load dependency module was not found.

Please note that I’m kind of a beginner.
What my program does is inputting information about the price and ticker of the stock and then doing some calculations and outputting the result. I made a class named stock that has instance variables which are the properties of each stock.
Source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <algorithm>
#include "Stock.h"
using namespace std;



int main() {
	cout <<"                                                Expectancy Calculator" << endl;
	int n, nClone,counter=0;
	cout << "How many expectancies do you want to calculate? " << flush;
	cin >> n;
	nClone = n;
	Stock* stock = new Stock [n];
	vector<double>expectancy;
	while (n--) {

		cout << "Enter ticker> " << flush;
		cin >> stock[counter].ticker;
		for (auto& x : stock[counter].ticker) //captialize ticker
			x = toupper(x);
		cout << "Enter current price> " << flush;
		cin >> stock[counter].currentPrice;
		cout << "Enter target price> " << flush;
		cin >> stock[counter].targetPrice;
		cout << "Enter price stop loss price> " << flush;
		cin >> stock[counter].lossPrice;
		cout << "Enter chance of success> " << flush;
		cin >> stock[counter].successChance;
		stock[counter].lossChance=1-stock[counter].successChance;
		
		stock[counter].expectancy = (((stock[counter].targetPrice- stock[counter].currentPrice)/ stock[counter].currentPrice)) * stock[counter].successChance - ((stock[counter].currentPrice-stock[counter].lossPrice) / stock[counter].currentPrice) * stock[counter].lossChance;
		expectancy.push_back(stock[counter].expectancy);
		counter++;
		if (n != 0) {
			cout << "Onto the next stock" << endl;
		}
		cout << "------------------------------------------------------------------------------------------------------------------------" << endl;

	}
	
	sort(expectancy.begin(), expectancy.end(),greater<float>());
	int j;
	
	printf("%c[4mResultsn%c[0m", 27, 27);

	for (int i = 0; i < nClone; i++) {
		for (int k = 0; k < nClone; k++) {
			if (stock[k].expectancy == expectancy[i]) {
				j = k;
			}
		}
		cout <<i+1 <<". " <<stock[j].ticker << ": " << expectancy[i]*100 <<"%" << endl;
	}

	return 0;
}

Last edited on

The magic 8 crystal ball says: «question too vague, include source code in post.»

If you’re using visual studio, you can attach a debugger to the program even when you run it outside of visual studio. Debug —> Attach to Process …
Put a breakpoint after the user input, and then you can step through the code to see when it crashes.

A guess: The difference is that your working directory is different when you directly run the exe outside of visual studio, so you are assuming a particular file exists when it doesn’t.

If you’re issue isn’t that it crashes but simply closes too quickly, then open your command prompt and run the program within the command prompt instead of having it use an evanescent window.

Edit: You added more information in your OP.
Those dependency walker errors might be false positives. If your program runs initially but crashes at a later point, I still suggest my method.

Last edited on

I ran Dependency Walker on the .exe file

Dependency Walker is an ooooooooold tool that doesn’t really work any more. There is an updated app available:

https://github.com/lucasg/Dependencies

I did what @Ganado suggested. I made debug and attached to the application process but I don’t really understand what’s happening. I’m kind of a beginner as mentioned above. Can you please clarify more what I exactly should do? Anyway, I provided the source code in the question above.

Last edited on

First note: You are using double. In a real program, you would never use floating-point numbers to represent exact money amount, but that’s a bit beyond the scope of what’s necessary here. But second, you use greater<float>() in your sort method. You should use greater<double> here, to match your data type.

Second note: If your exe were actually crashing, it would most likely generate an Event log in your event viewer. After running your exe and letting it «crash», if you open your Event log and navigate to Windows Logs —> Application (wait for it to load), do you see any error messages that relate to your exe?

Another minor note for the future: please don’t edit you OP more. It makes the thread less linear; just add additional information in new posts.

I suggest looking up a tutorial on Visual studio debugging or breakpoints. It’s hard to visually show you what exactly to do, beyond what I already mentioned: Start your exe. Then in Visual Studio, go to Debug —> Attach to Process —> then find your exe in the list, and click Attach. Then place a break point after your cin >> statements, and step through your code with F11 (or Debug —> Step Into) once you’re debugging.

I ran your code (creating my own Stock class)

1
2
3
4
5
6
7
8
9
10
class Stock {
public:
	string ticker;
	double currentPrice;
	double targetPrice;
	double lossPrice;
	double successChance;
	double lossChance;
	double expectancy;
};

I don’t see any flagrant errors other than the minor precision issue with float vs. double.

I think your problem is the well-known beginner issue: https://cplusplus.com/forum/beginner/1988/

You are double-clicking on the exe, which produces a temporary window, and once the program is over, this window disappears. This has been discussed ad nauseum in the linked thread above, but what I suggest is running the program through an existing cmd prompt instead of double-clicking it from your File explorer.

From your File explorer, go to the folder that contains your exe.
Then, click into the whitespace of the address bar, and type «cmd» and hit enter.
Then, in the command window, type the name of your exe and hit enter to run it.

Last edited on

@Ganado I figured it out! The problem got be solved when I inputted anything before returning 0. However, I don’t know why! You can see here in my new code that I’ve added int whatever; cin>>whatever; before returning 0 and it just worked! Have you got any idea why? Thanks for your support!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <vector>
#include <limits>
#include <iomanip>
#include <string>
#include <algorithm>
#include "Stock.h"
using namespace std;

string returnOrdinal(int number);

int main() {
	cout << "                                                Expectancy Calculator" << endl;
	int n, nClone, counter = 0;
	cout << "How many expectancies do you want to calculate? " << flush;
	cin >> n;
	nClone = n;
	Stock* stock = new Stock[n];
	vector<double>expectancy;
	while (n--) {

		cout << "Enter " << returnOrdinal(counter + 1) << " ticker> " << flush;
		cin >> stock[counter].ticker;
		for (auto& x : stock[counter].ticker) //captialize ticker
			x = toupper(x);
		cout << "Enter current price> " << flush;
		cin >> stock[counter].currentPrice;
		cout << "Enter target price> " << flush;
		cin >> stock[counter].targetPrice;
		cout << "Enter price stop loss price> " << flush;
		cin >> stock[counter].lossPrice;
		cout << "Enter chance of success> " << flush;
		cin >> stock[counter].successChance;
		stock[counter].lossChance = 1 - stock[counter].successChance;

		stock[counter].expectancy = (((stock[counter].targetPrice - stock[counter].currentPrice) / stock[counter].currentPrice)) * stock[counter].successChance - ((stock[counter].currentPrice - stock[counter].lossPrice) / stock[counter].currentPrice) * stock[counter].lossChance;
		expectancy.push_back(stock[counter].expectancy);
		counter++;
		if (n != 0) {
			cout << "Onto the next stock" << endl;
		}
		cout << "------------------------------------------------------------------------------------------------------------------------" << endl;

	}

	sort(expectancy.begin(), expectancy.end(), greater<double>());
	int j;

	cout << "Results" << endl;

	for (int i = 0; i < nClone; i++) {
		for (int k = 0; k < nClone; k++) {
			if (stock[k].expectancy == expectancy[i]) {
				j = k;
			}
		}
		cout << i + 1 << ". " << stock[j].ticker << ": " << expectancy[i] * 100 << "%" << endl;
	}
	int whatever;
	cin >> whatever;
	return 0;
}

string returnOrdinal(int number) {
	switch (number) {
	case 1: return "first";
	case 2: return "second";
	case 3: return "third";
	case 4: return "fourth";
	case 5: return "fifth";
	case 6: return "sixth";
	case 7: return "seventh";
	case 8: return "eighth";
	case 9: return "ninth";
	case 10: return "tenth";
	}
}

Last edited on

Slightly simplified:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
#include <functional>

struct Stock {
	std::string ticker;
	double currentPrice {};
	double targetPrice {};
	double lossPrice {};
	double successChance {};
	double lossChance {};
	double expectancy {};
};

std::string returnOrdinal(size_t number);

int main() {
	std::cout << "                                                Expectancy Calculatorn";

	size_t n {};

	std::cout << "How many expectancies do you want to calculate? ";
	std::cin >> n;

	const auto nClone {n};

	std::vector<Stock> stock(n);
	std::vector<double>expectancy;

	for (size_t counter = 0; counter < n; ++counter) {
		std::cout << "Enter " << returnOrdinal(counter + 1) << " ticker> ";
		std::cin >> stock[counter].ticker;

		for (auto& x : stock[counter].ticker)	//capitalize ticker
			x = static_cast<char>(std::toupper(static_cast<unsigned char>(x)));

		std::cout << "Enter current price> ";
		std::cin >> stock[counter].currentPrice;

		std::cout << "Enter target price> ";
		std::cin >> stock[counter].targetPrice;

		std::cout << "Enter price stop loss price> ";
		std::cin >> stock[counter].lossPrice;

		std::cout << "Enter chance of success> ";
		std::cin >> stock[counter].successChance;

		stock[counter].lossChance = 1 - stock[counter].successChance;
		stock[counter].expectancy = (((stock[counter].targetPrice - stock[counter].currentPrice) / stock[counter].currentPrice)) * stock[counter].successChance - ((stock[counter].currentPrice - stock[counter].lossPrice) / stock[counter].currentPrice) * stock[counter].lossChance;

		expectancy.push_back(stock[counter].expectancy);

		if (counter != n - 1)
			std::cout << "Onto the next stockn";

		std::cout << "------------------------------------------------------------------------------------------------------------------------n";
	}

	std::sort(expectancy.begin(), expectancy.end(), std::greater<double>());

	size_t j {};

	std::cout << "Resultsn";

	for (size_t i = 0; i < nClone; ++i) {
		for (size_t k = 0; k < nClone; ++k)
			if (stock[k].expectancy == expectancy[i])
				j = k;

		std::cout << i + 1 << ". " << stock[j].ticker << ": " << expectancy[i] * 100 << "%n";
	}
}

std::string returnOrdinal(size_t number) {

	const static char* const nums[] {"zero", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"};

	if (number <= 10)
		return nums[number];

	return ("Unknown");
}

Last edited on

when a program works in visual and not outside it, the first places I would look:

1) did you open a file and fail to validate if that went well with appropriate error messages? The path inside VS and the path outside are not the same, and a file that you think it should see may suddenly not be in its visible scope.

2) libraries. this is similar to the above — a dll or whatever that your program needs is visible in the tool and not outside it. These are much more obvious: it flat out tells you ‘cannot open blah.dll» somewhere in the error spew for the crash.

3) some sort of bug. the visual studio debugger env may do things to your program for debug reasons that make it work (eg initialize all to zero for you) which may not happen in (release mode or running outside the tool). To see this, try running the program in release mode in the tool. If it fails, it only works because the debugger is helping you, and you have some bug hunting to do.

4) microsoftisms. Here again these usually give you a blatant error message, often having something to do with a manifesto or other gibberish. You can fix the settings in the tool to make it knock it off, or you can move the required files around or fix the path (there that is again!) to cure it.

It sounds like you found the issue, thankfully. But these may help later. Your fix indicates that it maybe was just a speed of light problem. Your program is rather quick and small, it can open, execute, and close in the blink of an eye. Adding a cin makes it wait for you to type something, and you can see the output until you type. Does the program window close when you type something into whatever? If so, that is all it ever was. To ‘fix’ it you can open a cmd window and run inside that, where it will keep the output buffer on screen, or you can do what you did (effectively press a key to end program). All that is going on is the program (a console window) that has the output display is being closed before you can read it.

Last edited on

Bassel, it’s because the program is over once main returns. And once the program is over, the temporary window disappears. So you prevented the program from ending by having it wait for user input.

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Error module version mismatch
  • Error module vboxdrv not found
  • Error module rewrite does not exist
  • Error module php8 does not exist
  • Error module php7 does not exist