String Streams
The stringstream is a class that is useful for extracting data from or writing formatted data to strings.
A very common question, for example is this: ``How do I convert a string to a number ? ''. Of course, there's no way to do so in general, since not all strings look like numbers. But it's certainly not unusual that we'd want to extract a number from a string. Note that the g++ compiler ships without the sstream header.
FAQ: How Do I Convert String To Number ?
1 #include <iostream>
2 #include <sstream>
3 using namespace std;
4 int main()
5 {
6 int a;
7 string s = "456";
8 istringstream sin(s);
9 sin >> a;
10 cout << a << endl;
11 return 0;
12 }
The istringstream class is an input stream attached to a string. The constructor copies the string s into its private buffer, and then we may extract data from it using regular stream semantics, in this case we use
sin>>a.
FAQ: How Do I Convert A Number To A String ?
or how do I do ``sprintf'' in C++ ?
You may have guessed -- the answer is to use an ostringstream. This data type behaves in a similar way to the istringstream. The main difference is that there is an extra method, str(). This method returns the string that lies in the ostringstream object. There's also a verision of str() that takes a string argument -- this initialises the streams underlying string buffer to that argument. This is commonly used to clear a stream for reuse -- one can call mystream.str("");
1 #include <sstream>
2 #include <iostream>
3 int main()
4 {
5 std::ostringstream strout;
6 int x = 42;
7 strout << "The answer to the question is " << 42 << std::endl;
8 cout << strout.str() << endl;
9 strout.str("");
10 strout << 53.2;
11 cout << strout.str() << endl;
12 return 0;
13 }
Using Stringstreams To Parse Input
A problem that often comes up is this: suppose you have written the following code:
1 #include <iostream>
2
3 using namespace std;
4 int main()
5 {
6 int x;
7 do
8 cout << "Enter a positive integer (0 to quit)" << endl;
9 while ( cin >> x && x != 0 );
10 return 0;
11 }
What happens if the user enters
2 3
Or worse, if they enter:
5.0
The problem is that the extraction operator does not expect each item extracted to be on a seperate line. So if you do expect this, you need to be explicit about it in your code. The way to do this is use getline() to read a line of input into a string and then use that string to create an istringstream from which we can extract data. After we've extracted the data we need, we can check for trailing garbage. Here's an example:
1 #include <sstream>
2 #include <iostream>
3
4 using std::cin;
5 using std::cout;
6 using std::end;
7
8 int main()
9 {
10 int x;
11 char ch;
12 std::string myString;
13 while (getline ( cin, myString ))
14 {
15 std::istringstream strin(myString);
16 strin >> x;
17 if (!strin)
18 cout << "Bad input" << endl;
19 else if ( strin >> ch )
20 cout << "Bad input" << endl;
21 else
22 cout << "You entered: " << x << endl;
23 }
24 return 0;
25 }
Some notes:
* The istringstream object is declared within the loop, so its scope is the block of the loop. So a new istringstream object is created and the old one is destroyed for each iteration of the loop.
* The test (!strin) checks to see if the stream is in an error state.
* The attempt to extract a character is a test to see if there's anything left in the stream after we extract an integer. Note that this ignores whitespace (which is the desired effect in this case)
* If there are no problems, then the extraction was succesful.
strstream considered harmful
There exists a deprecated class similar to stringstream that is called strstream. Do not confuse these two classes. They are not the same. strstream has a very error prone interface because of the way it handles memory. One problem is that it does not append trailing nulls when str() is called. So you must append a trailing null, or std::ends. Another important thing to remember is that if you use ostrstream with a dynamic buffer, like this:
std::ostrstream strout;
strout << "The answer is ..." << 42 << std::endl << std::ends;
strout.str();
Then calling str has the peculiar side effect that the caller is responsible for managing the memory allocated by strout's buffer, which is pretty silly since the caller does not know how the memory was allocated (it may be allocated using malloc() or new). So to make the stupid thing take its memory back, one makes the following call:
strout.freeze(0);
It's worth mentioning that there is another, safer way to use ostrstream and that is to use it with a static buffer. If you do this, you don't need to deal with this freeze() nonsense. To do this, call the constructor that takes a character array as an argument.
char a[100];
std::ostrstream strout(a,100);
strout << "the answer is" << 42 << std::endl << std::ends;
std::cout << a << std::endl;
摘要: Here is an example validator for bean class User.
RegisterAction-validation.xml
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1&...
阅读全文
摘要: Here is a interceptor example in ssh structure web application.
First of all, I write a login interceptor and add it into default interceptor stack. It only can print out on console without any oth...
阅读全文
摘要: In this article, I will introduce 3 ways in writing validators in Struts2-Spring-Hibernate application.
First of all, create package com.ssh.bean and create a bean named 'User' under this package:
...
阅读全文
摘要: It's only the simpliest Struts2-Spring-Hibernate web application which only has a login function. I will call it SSH which is apparently different from the one appeared in Linux. I assume the installa...
阅读全文
I give a basic helloworld Spring example which references the example from "Spring in Action" chapter2.
Of course JDK must be installed, %JAVA_HOME% and both %Path% and %Classpath% are filled with correct path.
Maven2 Installation
Because it's the first example showing how Maven works in Spring, all the mandatory steps are included without other optional configurations.
Windows 2000/XP/Vista
1. Unzip the distribution archive, i.e. apache-maven-2.0.10-bin.zip to the directory F:\Development\j2eelib\apache_maven\apache-maven-2.1.0
2. Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the "Advanced" tab, and the "Environment Variables" button, then adding the M2_HOME variable in the user variables with the value F:\Development\j2eelib\apache_maven\apache-maven-2.1.0
Be sure to omit any quotation marks around the path even if it contains spaces. Note: For Maven < 2.0.9, also be sure that the M2_HOME doesn't have a '\' as last character.
3. In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%"bin.
4. Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
5. In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line.
6. In the same dialog, make sure that JAVA_HOME exists.
7. Open a new command prompt (Winkey + R then type cmd) and run mvn --version to verify that it is correctly installed.
Create First "Helloworld" Spring Project by Maven2.
Step 1.
Open windows cmd and go into a directory which is prepared to be the project's location.
e.g. F:\Development\Java\maven\
mvn archetype:create -DgroupId=com.springinaction.chapter01 -DartifactId=springinaction
Step 2.
Go into sub-directory springinaction which is created by mvn command above: cd springinaction
It's worth to mention that checking all the available dependencies on Maven's website as well as their version number is necessary:
http://mvnrepository.com/artifact/org.springframework/spring
Config pom.xml first:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>com.springinaction.chapter01</groupId>
5 <artifactId>springinaction</artifactId>
6 <packaging>jar</packaging>
7 <version>1.0-SNAPSHOT</version>
8 <name>springinaction</name>
9 <url>http://maven.apache.org</url>
10 <dependencies>
11 <dependency>
12 <groupId>junit</groupId>
13 <artifactId>junit</artifactId>
14 <version>3.8.1</version>
15 <scope>test</scope>
16 </dependency>
17
18 <!-- Choose to add each module as a dependency as it's needed.-->
19 <dependency>
20 <groupId>org.springframework</groupId>
21 <artifactId>spring</artifactId>
22 <version>2.5.6</version>
23 </dependency>
24
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-aop</artifactId>
28 <version>2.5.6</version>
29 </dependency>
30
31 <dependency>
32 <groupId>org.springframework</groupId>
33 <artifactId>spring-beans</artifactId>
34 <version>2.5.6</version>
35 </dependency>
36
37 <dependency>
38 <groupId>org.springframework</groupId>
39 <artifactId>spring-core</artifactId>
40 <version>2.5.6</version>
41 </dependency>
42
43 </dependencies>
44 </project>
Edit App.java which have been created already or create any new java which is needed.
1 package com.springinaction.chapter01;
2 import org.springframework.beans.factory.BeanFactory;
3 import org.springframework.beans.factory.xml.XmlBeanFactory;
4 import org.springframework.core.io.FileSystemResource;
5
6 import com.springinaction.chapter01.service.GreetingService;
7
8 public class App{
9 public static void main( String[] args ){
10 BeanFactory factory = new XmlBeanFactory(new FileSystemResource("hello.xml"));
11
12 GreetingService greetingService = (GreetingService) factory.getBean("greetingService");
13 greetingService.sayGreeting();
14 }
15 }
Create service directory under com.springinaction.chapter01 and create GreetingService.java:
1 package com.springinaction.chapter01.service;
2
3 public interface GreetingService{
4 void sayGreeting();
5
Create serviceimpl directory under com.springinaction.chapter01.service and create GreetingServiceImpl.java
1 package com.springinaction.chapter01.service.serviceimpl;
2
3 import com.springinaction.chapter01.service.GreetingService;
4
5 public class GreetingServiceImpl implements GreetingService{
6 private String greeting;
7 public GreetingServiceImpl(){}
8 public GreetingServiceImpl(String greeting){
9 this.greeting = greeting;
10 }
11 public void sayGreeting(){
12 System.out.println(greeting);
13 }
14 public void setGreeting(String greeting){
15 this.greeting = greeting;
16 }
17 }
The directories structure should be like this in the red square.
The directories service and serviceimpl are created manually, but others are created by Maven automatically.
Create hello.xml under root directory springinaction
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="
5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
6
7 <bean id="greetingService" class="com.springinaction.chapter01.service.serviceimpl.GreetingServiceImpl">
8 <property name="greeting" value="Hello World in Spring Bean!"/>
9 </bean>
10
11 </beans>
Step3:
Under cmd mode and in the root directory springinaction:
mvn compile
mvn test
or
mvn package
And then:
java -cp target/springinaction-1.0-SNAPSHOT.jar;F:\Development\j2eelib\spring-framework-2.5.6\dist\spring.jar;F:\Development\j2eelib\spring-framework-2.5.6\lib\jakarta-commons\commons-logging.jar;F:\Development\j2eelib\spring-framework-2.5.6\dist\modules\spring-aop.jar;F:\Development\j2eelib\spring-framework-2.5.6\dist\modules\spring-beans.jar;F:\Development\j2eelib\spring-framework-2.5.6\dist\modules\spring-core.jar com.springinaction.chapter01.App
Notice: Change your cp parameters according to specific location in your environment.
It is important to include all necessary jar files which are needed in the project.
-cp means classpath.
Result:
After debug, make clean is necessary which will delete all compiled classes, jar and their directories.
mvn clean
摘要: Normal
0
7.8 pt
0
2
false
false
false
EN-US
ZH-CN
X-NONE
MicrosoftInternetExplorer4
...
阅读全文
摘要: v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
Normal
0
7.8 pt
0
2
false
fals...
阅读全文
Due to the
excellent performance by sentence rank, a further experiment is conducted:
applying sentence rank on real news web pages. In this section, due to the
length of report, only implement undirected graph and 10 terms per query, the
following success retrieve rate shows a high percentage value when the cosine
similarity on 2 web pages is applied by using 4.1and 4.2. 10 terms a query means only take first 10
words in the selected sentence including stop words which is consistent with
section 4.6. Unlike locating the exact address of a web page itself, this
comparison leads to find similar topic document by comparing 2 different URL
web pages, the details are all introduced in section 3.4.
4.1
4.2
Meanwhile, there
are 3 search engines employed in this section: Yahoo News Search, Yahoo Web
Search and Google Web Search. Unlike from section 4.6 to section 4.1 which only
count URL string match as success retrieval, section 4.7 take document
similarity into consideration, and if equation 4.2’s value is bigger than 0.9, which is also
permitted in S. T Park and Xiaojun Wang’s research, a success retrieval is
considered effective. There are 183 pages in this section which are all from
May 4, 2009, Yahoo News, and all related URL addresses are listed in Appendix
D.
|
Success Counts
|
Success Rate
|
Yahoo News Search
|
171
|
93.44%
|
Yahoo Web Search
|
178
|
97.27%
|
Google Web Search
|
177
|
96.72%
|
Table4.29
(a) (b)
Figure4.32
As Figure4.32’s (b) shows, the success rate is above 90%
which satisfies the project’s initial requirements by applying a single text
retrieval method.
摘要: v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
Normal
0
7.8 pt
0
2
false
fals...
阅读全文